Windows forms combobox значение по умолчанию

In windows form, It has a ComboBox, Which have data binded by the DataSource. When going to set the text property for a ComboBox. Selected ComboBox -> Property -> Text : "--Select--". Design...

Suppose you bound your combobox to a List<Person>

List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});

cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;

At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource

pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;

Of course this means that you need to add a checking code when you try to use the info from the combobox

if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
    MessageBox.Show("Please select a person name");
else
    ...... 

The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection

In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to

DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";    
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);

0 / 0 / 1

Регистрация: 10.10.2011

Сообщений: 42

1

08.01.2012, 16:04. Показов 69072. Ответов 6


Есть Combobox, у него допустим 25 чисел от 00 — 24. Нужно, что бы при старте программы там автоматически появлялось 00, а потом юзер при желании может изменить.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



kolorotur

Эксперт .NET

16746 / 12498 / 3285

Регистрация: 17.09.2011

Сообщений: 20,732

08.01.2012, 16:08

2

Лучший ответ Сообщение было отмечено как решение

Решение

C#
1
2
3
4
5
public Form1()
{
   InitializeComponen();
   comboBox1.SelectedItem = "00";
}



5



MrLOLS

23 / 23 / 4

Регистрация: 21.11.2010

Сообщений: 77

30.05.2012, 21:10

3

C#
1
comboBox1.SelectedIndex=0;



7



AlexSolder

0 / 0 / 0

Регистрация: 25.02.2016

Сообщений: 5

10.06.2016, 18:50

4

Не знаю, как у людей получалось такими методами делать, у меня так вышло:

C#
1
comboBox1.Text = comboBox1.Items[9].ToString();

Здесь индексом указываете нужный вам элемент



0



Эксперт .NET

16746 / 12498 / 3285

Регистрация: 17.09.2011

Сообщений: 20,732

12.06.2016, 12:17

5

Цитата
Сообщение от AlexSolder
Посмотреть сообщение

Не знаю, как у людей получалось такими методами делать

Люди просто совсем другое делали: устанавливали выбранный элемент списку.
А вы получаете значение уже выбранного элемента и помещаете его в текстовое поле.



0



6 / 7 / 0

Регистрация: 09.05.2013

Сообщений: 148

17.09.2020, 05:27

6

А есть соответствующее свойство в конструкторе?



0



URAHOV

2 / 2 / 0

Регистрация: 27.12.2015

Сообщений: 45

19.12.2020, 07:27

7

// file: Form1.cs

C#
1
2
3
4
5
6
7
8
private void Form1_Load(object sender, EventArgs e)
        {
            // после загрузки формы устанавливает значение
            //по умолчанию 1-ый эл-т в списке
 
            comboBox1.SelectedIndex = 0;
 
        }

// file: Form1.Designer.cs

C#
1
2
3
4
// 
// comboBox1
// 
this.comboBox1.SelectedIndex = 0;



0



Hi here i want to bind some values to check box dynamically.

dataset ds = //getting emp values form database;
cbemp.ValueMember = "empid";
cbemp.DisplayMember = "empname";
cbemp.DataSource = ds.Tables["emp"];

it is working fine. But i want to add

«Select emplyoee» as a default value of check box .

But my check box directly adding values like

a1
a2
a3

like this.

I tried like this

cbemp.Items.Insert(0, "Select emplyoee");

but it is not working

how can i add it?

Fredrik Mörk's user avatar

Fredrik Mörk

154k29 gold badges288 silver badges342 bronze badges

asked Aug 31, 2009 at 11:55

Nagu's user avatar

When you use databinding, you cannot «manually» add or remove items. The only way to achieve what you want using databinding is to insert a row first in the DataTable with the desired value, or to populate the combobox by code (add the «Select employee» item and then iterate of the the DataTable rows to add the records).

Perhaps something like this could work:

// create new row for "Select employee"
DataRow row = ds.Tables["emp"].NewRow();
row["empid"] = -1;
row["empname"] = "Select employee";
// insert the row at the top of the table
ds.Tables["emp"].Rows.InsertAt(row, 0);
// do the databinding
cbemp.ValueMember = "empid";
cbemp.DisplayMember = "empname";
cbemp.DataSource = ds.Tables["emp"];

I don’t use databinding much, so there may be drawbacks with this that I am unaware of (but I am confident that the community will point that out in that case).

answered Aug 31, 2009 at 12:03

Fredrik Mörk's user avatar

Fredrik MörkFredrik Mörk

154k29 gold badges288 silver badges342 bronze badges

0

Inserting data in your data source is a bad idea. It promotes breaking your layers’ abstractions and may lead to some issues if you are using the same data source elsewhere.

Instead, you can easily extend the ComboBox to show a «Please select» message when it has no item selected.

I blogged about this issue and provided the code here : http://www.byteauthor.com/2010/08/inner-label-in-combobox/

answered Aug 3, 2010 at 19:41

Kevin Coulombe's user avatar

Kevin CoulombeKevin Coulombe

1,4971 gold badge17 silver badges35 bronze badges

I think you’d have to add it to the underlying datatable (ds.Tables[«emp»]) for it to appear as an entry in the list when you’re using databound controls.

answered Aug 31, 2009 at 12:03

MartW's user avatar

MartWMartW

12.3k3 gold badges42 silver badges68 bronze badges

When your control is data bound you cannot add items manually I think.

To work around this problem you could either add a new item to your data source, or you could add the items manually.

answered Aug 31, 2009 at 12:04

Rune Grimstad's user avatar

Rune GrimstadRune Grimstad

35.3k10 gold badges62 silver badges76 bronze badges

The above accepted solution is better, but one trick that might come in handy sometimes is to Union a «fake» record to the SQL that is returning the recordset for the data-binding. In this case, something like:

select 0 as empid, 'Please select' as empname
union
select empid, empname from emp
order by empid

Of course you will have to protect the database from accidentally writing the «0» record back (e.g. if the user doesn’t make a selection), but that isn’t too hard.

answered Oct 25, 2011 at 5:20

Andrew Jens's user avatar

Andrew JensAndrew Jens

1,03215 silver badges16 bronze badges

if ComboBoxStyle is set to DropDownList (so user cannot edit combobox) then the easiest way to make sure the user selects an item is to set selectedIndex=-1, you can always add «Please Select» etc ABOVE the combobox.

answered Oct 1, 2013 at 20:45

Harry's user avatar

HarryHarry

1,5751 gold badge10 silver badges12 bronze badges

In my case ( databinded combobox ) i solved the problem like this. Of course the best way is the Kevin Coulombe one.

ComboBox.SelectedIndex = -1;
ComboBox.Text = "Please, select something";

With a bit of code you can manage this scenario pretty easy.

answered Aug 19, 2014 at 14:47

Wanny Miarelli's user avatar

Wanny MiarelliWanny Miarelli

7062 gold badges15 silver badges30 bronze badges

Hi here i want to bind some values to check box dynamically.

dataset ds = //getting emp values form database;
cbemp.ValueMember = "empid";
cbemp.DisplayMember = "empname";
cbemp.DataSource = ds.Tables["emp"];

it is working fine. But i want to add

«Select emplyoee» as a default value of check box .

But my check box directly adding values like

a1
a2
a3

like this.

I tried like this

cbemp.Items.Insert(0, "Select emplyoee");

but it is not working

how can i add it?

Fredrik Mörk's user avatar

Fredrik Mörk

154k29 gold badges288 silver badges342 bronze badges

asked Aug 31, 2009 at 11:55

Nagu's user avatar

When you use databinding, you cannot «manually» add or remove items. The only way to achieve what you want using databinding is to insert a row first in the DataTable with the desired value, or to populate the combobox by code (add the «Select employee» item and then iterate of the the DataTable rows to add the records).

Perhaps something like this could work:

// create new row for "Select employee"
DataRow row = ds.Tables["emp"].NewRow();
row["empid"] = -1;
row["empname"] = "Select employee";
// insert the row at the top of the table
ds.Tables["emp"].Rows.InsertAt(row, 0);
// do the databinding
cbemp.ValueMember = "empid";
cbemp.DisplayMember = "empname";
cbemp.DataSource = ds.Tables["emp"];

I don’t use databinding much, so there may be drawbacks with this that I am unaware of (but I am confident that the community will point that out in that case).

answered Aug 31, 2009 at 12:03

Fredrik Mörk's user avatar

Fredrik MörkFredrik Mörk

154k29 gold badges288 silver badges342 bronze badges

0

Inserting data in your data source is a bad idea. It promotes breaking your layers’ abstractions and may lead to some issues if you are using the same data source elsewhere.

Instead, you can easily extend the ComboBox to show a «Please select» message when it has no item selected.

I blogged about this issue and provided the code here : http://www.byteauthor.com/2010/08/inner-label-in-combobox/

answered Aug 3, 2010 at 19:41

Kevin Coulombe's user avatar

Kevin CoulombeKevin Coulombe

1,4971 gold badge17 silver badges35 bronze badges

I think you’d have to add it to the underlying datatable (ds.Tables[«emp»]) for it to appear as an entry in the list when you’re using databound controls.

answered Aug 31, 2009 at 12:03

MartW's user avatar

MartWMartW

12.3k3 gold badges42 silver badges68 bronze badges

When your control is data bound you cannot add items manually I think.

To work around this problem you could either add a new item to your data source, or you could add the items manually.

answered Aug 31, 2009 at 12:04

Rune Grimstad's user avatar

Rune GrimstadRune Grimstad

35.3k10 gold badges62 silver badges76 bronze badges

The above accepted solution is better, but one trick that might come in handy sometimes is to Union a «fake» record to the SQL that is returning the recordset for the data-binding. In this case, something like:

select 0 as empid, 'Please select' as empname
union
select empid, empname from emp
order by empid

Of course you will have to protect the database from accidentally writing the «0» record back (e.g. if the user doesn’t make a selection), but that isn’t too hard.

answered Oct 25, 2011 at 5:20

Andrew Jens's user avatar

Andrew JensAndrew Jens

1,03215 silver badges16 bronze badges

if ComboBoxStyle is set to DropDownList (so user cannot edit combobox) then the easiest way to make sure the user selects an item is to set selectedIndex=-1, you can always add «Please Select» etc ABOVE the combobox.

answered Oct 1, 2013 at 20:45

Harry's user avatar

HarryHarry

1,5751 gold badge10 silver badges12 bronze badges

In my case ( databinded combobox ) i solved the problem like this. Of course the best way is the Kevin Coulombe one.

ComboBox.SelectedIndex = -1;
ComboBox.Text = "Please, select something";

With a bit of code you can manage this scenario pretty easy.

answered Aug 19, 2014 at 14:47

Wanny Miarelli's user avatar

Wanny MiarelliWanny Miarelli

7062 gold badges15 silver badges30 bronze badges

Привет, я хочу динамически привязать некоторые значения к флажку.

dataset ds = //getting emp values form database;
cbemp.ValueMember = "empid";
cbemp.DisplayMember = "empname";
cbemp.DataSource = ds.Tables["emp"];

он работает нормально. Но я хочу добавить

«Выбрать emplyoee» в качестве значения флажка по умолчанию.

Но мой флажок напрямую добавляет такие значения, как

a1
a2
a3

как это.

Я пробовал вот так

cbemp.Items.Insert(0, "Select emplyoee");

Но это не работает

как я могу это добавить?

7 ответы

Когда вы используете привязку данных, вы не можете «вручную» добавлять или удалять элементы. Единственный способ добиться желаемого с помощью привязки данных — сначала вставить строку в DataTable с желаемым значением или для заполнения поля со списком с помощью кода (добавьте элемент «Выбрать сотрудника», а затем выполните итерацию DataTable строк для добавления записей).

Возможно, что-то вроде этого могло бы сработать:

// create new row for "Select employee"
DataRow row = ds.Tables["emp"].NewRow();
row["empid"] = -1;
row["empname"] = "Select employee";
// insert the row at the top of the table
ds.Tables["emp"].Rows.InsertAt(row, 0);
// do the databinding
cbemp.ValueMember = "empid";
cbemp.DisplayMember = "empname";
cbemp.DataSource = ds.Tables["emp"];

Я не часто использую привязку данных, поэтому могут быть недостатки, о которых я не подозреваю (но я уверен, что сообщество укажет на это в этом случае).

ответ дан 31 авг.

Вставка данных в ваш источник данных — плохая идея. Это способствует нарушению абстракций ваших слоев и может привести к некоторым проблемам, если вы используете тот же источник данных в другом месте.

Вместо этого вы можете легко расширить ComboBox, чтобы отображать сообщение «Пожалуйста, выберите», когда в нем не выбран ни один элемент.

Я писал об этой проблеме и предоставил код здесь: http://www.byteauthor.com/2010/08/inner-label-in-combobox/

ответ дан 03 авг.

Я думаю, вам придется добавить его в базовую таблицу данных (ds.Tables [«emp»]), чтобы она отображалась как запись в списке, когда вы используете элементы управления привязкой к данным.

ответ дан 31 авг.

Когда ваш элемент управления привязан к данным, я думаю, вы не можете добавлять элементы вручную.

Чтобы обойти эту проблему, вы можете добавить новый элемент в свой источник данных или добавить элементы вручную.

ответ дан 31 авг.

Вышеупомянутое принятое решение лучше, но одна уловка, которая иногда может пригодиться, — объединить «фальшивую» запись в SQL, который возвращает набор записей для привязки данных. В этом случае что-то вроде:

select 0 as empid, 'Please select' as empname
union
select empid, empname from emp
order by empid

Конечно, вам придется защитить базу данных от случайной перезаписи нулевой записи (например, если пользователь не сделает выбор), но это не так уж сложно.

ответ дан 25 окт ’11, 06:10

если для ComboBoxStyle установлено значение DropDownList (чтобы пользователь не мог редактировать поле со списком), то самый простой способ убедиться, что пользователь выбирает элемент, — установить selectedIndex = -1, вы всегда можете добавить «Пожалуйста, выберите» и т. д. НАД над полем со списком.

ответ дан 01 окт ’13, 21:10

В моем случае (поле со списком с привязкой к данным) я решил проблему следующим образом. Конечно, лучший способ — это вариант Кевина Куломба.

ComboBox.SelectedIndex = -1;
ComboBox.Text = "Please, select something";

С небольшим количеством кода вы можете довольно легко справиться с этим сценарием.

ответ дан 19 авг.

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

c#
winforms
combobox

or задайте свой вопрос.

У меня есть несколько элементов в моей коллекции элементов ComboBox, и я хотел бы выбрать один элемент из этого списка и установить его в качестве элемента по умолчанию — при запуске приложения — этот элемент уже находится в comboBox.

Я пытаюсь что-то подобное:

SelectPrint11.SelectedIndex=2;

но ошибка такова:

System.ArgumentOutOfRangeException: InvalidArgument=Value of '2' is not valid for 'SelectedIndex'

Редактировать:

В mylist 3 пункта: Printer1, Printer2, Printer3. Все они добавлены в ComboBox Properties → Items → Collection

4b9b3361

Ответ 1

Вы можете установить с помощью SelectedIndex

comboBox1.SelectedIndex= 1;

ИЛИ

SelectedItem

comboBox1.SelectedItem = "your value"; // 

Последний не будет генерировать исключение, если это значение недоступно в combobox

ИЗМЕНИТЬ

Если выбранное значение не является конкретным, вам будет лучше с этим

comboBox1.SelectedIndex = comboBox1.Items.Count - 1;

Ответ 2

Помните, что коллекции в С# основаны на нуле (другими словами, элемент первый в коллекции находится в позиции ноль). Если у вас есть два элемента в вашем списке, и вы хотите выбрать последний элемент, используйте SelectedIndex = 1.

Ответ 3

Это означает, что ваш выбранный индекс выходит за пределы диапазона элементов в выпадающем списке. Массив элементов в вашем поле со списком с нулевым, поэтому, если у вас есть 2 элемента, это пункт 0 и пункт 1.

Ответ 4

private void comboBox_Loaded(object sender, RoutedEventArgs e)
{
 Combobox.selectedIndex= your index;
}

ИЛИ, если вы хотите отобразить некоторое значение после сравнения с combobox

 foreach (var item in comboBox.Items)
            {
                if (item.ToString().ToLower().Equals("your item in lower"))
                {
                    comboBox.SelectedValue = item;
                }
            }

Надеюсь, это поможет, это работает для меня.

Ответ 5

сначала перейдите к загрузке формы, где находится ваш comboBox,

затем попробуйте этот код

comboBox1.SelectedValue = 0;//показывает первый элемент в вашей коллекции

Последнее обновление: 31.10.2015

Элемент ComboBox образует выпадающий список и совмещает функциональность компонентов ListBox и TextBox. Для хранения элементов списка в ComboBox также предназначено свойство
Items.

Подобным образом, как и с ListBox, мы можем в окне свойств на свойство Items и нам отобразится окно для добавления элементов ComboBox:

Добавление элементов в ComboBox

И как и с компонентом ListBox, здесь мы также можем программно управлять элементами.

Добавление элементов:

// добавляем один элемент
comboBox1.Items.Add("Парагвай");
// добавляем набор элементов
comboBox1.Items.AddRange(new string[] { "Уругвай", "Эквадор" });
// добавляем один элемент на определенную позицию
comboBox1.Items.Insert(1, "Боливия");

При добавлении с помощью методов Add / AddRange все новые элементы помещаются в конец списка. Однако если мы зададим у ComboBox свойство
Sorted равным true, тогда при добавлении будет автоматически производиться сортировка.

Удаление элементов:

// удаляем один элемент
comboBox1.Items.Remove("Аргентина");
// удаляем элемент по индексу
comboBox1.Items.RemoveAt(1);
// удаляем все элементы
comboBox1.Items.Clear();

Мы можем получить элемент по индексу и производить с ним разные действия. Например, изменить его:

comboBox1.Items[0] = "Парагвай";

Настройка оформления ComboBox

С помощью ряда свойств можно настроить стиль оформления компонента. Так, свойство DropDownWidth задает ширину выпадающего списка.
С помощью свойства DropDownHeight можно установить высоту выпадающего списка.

Еще одно свойство MaxDropDownItems позволяет задать число видимых элементов списка — от 1 до 100. По умолчанию это число равно 8.

Другое свойство DropDownStyle задает стиль ComboBox. Оно может принимать три возможных значения:

  • Dropdown: используется по умолчанию. Мы можем открыть выпадающий список вариантов при вводе значения в текстовое поле или нажав на кнопку со стрелкой
    в правой части элемента, и нам отобразится собственно выпадающий список, в котором можно выбрать возможный вариант

  • DropdownList: чтобы открыть выпадающий список, надо нажать на кнопку со стрелкой в правой стороне элемента

  • Simple: ComboBox представляет простое текстовое поле, в котором для перехода между элементами мы можем использовать клавиши
    клавиатуры вверх/вниз

Элемент ComboBox в Windows Forms

Событие SelectedIndexChanged

Наиболее важным событием для ComboBox также является событие SelectedIndexChanged, позволяющее отследить выбор элемента в списке:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;    
    }

    void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string selectedState = comboBox1.SelectedItem.ToString();
        MessageBox.Show(selectedState);
    }
}

Здесь также свойство SelectedItem будет ссылаться на выбранный элемент.

C# ComboBox Control

The ComboBox control provides combined functionality of a text box and a listbox in a single control. Only one list item is displayed at one time in a ComboBox and rest of the available items are loaded in a drop down list.

Creating a ComboBox


We can create a ComboBox control using a Forms designer at design-time or using the ComboBox class in C# code at run-time.

To create a ComboBox control at design-time, you simply drag and drop a ComboBox control from Toolbox to a Form in Visual Studio. After you drag and drop a ComboBox on a Form, the ComboBox looks like Figure 1.  

ComboBox In C#

Figure 1

Once a ComboBox is on the Form, you can move it around and resize it and set its properties and events using the Properties and Events windows.

Creating a ComboBox control at run-time includes creating an instance of ComboBox class, set its properties and add ComboBox instance to the Form controls.

First step to create a dynamic ComboBox is to create an instance of ComboBox class.

The following code snippet creates a ComboBox control object.

  1. ComboBox comboBox1 = new ComboBox();  

In the next step, you set properties of a ComboBox control.

The following code snippet sets location, width, height, background color, foreground color, Text, Name, and Font properties of a ComboBox.

  1. comboBox1.Location = new System.Drawing.Point(20, 60);
  2. comboBox1.Name = «comboBox1»;
  3. comboBox1.Size = new System.Drawing.Size(245, 25);
  4. comboBox1.BackColor = System.Drawing.Color.Orange;  
  5. comboBox1.ForeColor = System.Drawing.Color.Black; 

Once the ComboBox control is ready with its properties, the next step is to add the ComboBox to a Form.

To do so, we use Form.Controls.Add method.

The following code snippet adds a ComboBox control to the current Form.

  1. Controls.Add(comboBox1);  

Setting ComboBox Properties


Alternatively, you can set control properites at design time. The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item. The Properties window looks like Figure 2.

ComboBox In C#

Figure 2

Name

Name property represents a unique name of a ComboBox control. It is used to access control in the code. The following code snippet sets and gets the name and text of a ComboBox control.

  1. comboBox1.Name = «comboBox1»;  

Location, Height, Width and Size

The Location property is a type of Point that specifies the starting position of the ComboBox on a Form. You may also use Left and Top properties to specify the location of a control from the left top corner of the Form. The Size property specifies the size of the control. We can also use Width and Height property instead of Size property. The following code snippet sets Location, Width, and Height properties of a ComboBox control.

  1. comboBox1.Location = New System.Drawing.Point(12, 12);  
  2. comboBox1.Size = New System.Drawing.Size(300, 25);  
  3. comboBox1.Width = 300;  
  4. comboBox1.Height = 25;

DropDownHeight and DropDownWidthYou can control the size of the dropdown area of a ComboBox. The DropDownHeight and DropDownWidth properties represent the height and width of the dropdown area in pixel respectively. If the DropDownWidth and DropDownHeight properties are less than the Width and Height values, they will not be applicable. If all the items do not fit in the size of the dropdown area, the scrollbars will appear as you can see from Figure 3.

ComboBox In C#

Figure 3

The following code snippet sets the height and width of the dropdown area of a ComboBox.

  1. comboBox1.DropDownHeight = 50;  
  2. comboBox1.DropDownWidth = 300;  

Font

Font property represents font of text of a ComboBox control. If you click on the Font property in Properties window, you will see Font name, size and other font options.

  1. comboBox1.Font = new Font(«Georgia», 16);  

Background and Foreground

BackColor and ForeColor properties are used to set background color and foreground color of a ComboBox respectively. If you click on these properties in Properties window, the Color Dialog pops up.

Alternatively, you can set background color and foreground color at run-time. The following code snippet sets BackColor and ForeColor properties.

  1. comboBox1.BackColor = System.Drawing.Color.Orange;  
  2. comboBox1.ForeColor = System.Drawing.Color.Black;  

The new ComboBox with background and foreground looks like Figure 4.

ComboBox In C#

Figure 4

ComboBox Items


The Items property is used to add and access items in a ComboBox. We can add items to a ComboBox at design-time from Properties Window by clicking on Items Collection as you can see in Figure 5.

ComboBox In C#

Figure 5

When you click on the Collections, the String Collection Editor window will pop up where you can type strings. Each line added to this collection will become a ComboBox item. I add four items as you can see from Figure 6.

ComboBox In C#

Figure 6

The ComboBox looks like Figure 7.

ComboBox In C#

Figure 7

Alternatively, you can add same items at run-time by using the following code snippet.

  1. comboBox1.Items.Add(«Mahesh Chand»);  
  2. comboBox1.Items.Add(«Mike Gold»);  
  3. comboBox1.Items.Add(«Praveen Kumar»);  
  4. comboBox1.Items.Add(«Raj Beniwal»);  

Getting All Items

To get all items of a control, we use Items property that is a collection of items.

The following code snippet loops through all items and adds item contents to a StringBuilder and displays in a MessageBox.

  1. private void GetItemsButton_Click(object sender, EventArgs e)  
  2. {  
  3. StringBuilder sb = new StringBuilder();  
  4. foreach (string name in Combo1.Items)  
  5.    {  
  6.       sb.Append(name);  
  7.       sb.Append(» «);  
  8.    }  
  9. MessageBox.Show(sb.ToString());  
  10. }  

Selected Text and Item

Text property is used to set and get text of a ComboBox. The following code snippet sets and gets current text of a ComboBox.

  1. comboBox1.Text = «Mahesh Chand»;  
  2. MessageBox.Show(comboBox1.Text);  

We can also get text associated with currently selected item by using Items property.

  1. string selectedItem = comboBox1.Items[comboBox1.SelectedIndex].ToString();  

Why the value of ComboBox.SelectedText is Empty?

SelectedText property gets and sets the selected text in a ComboBox only when a ComboBox has focus on it. If the focus moves away from a ComboBox, the value of SelectedText will be an empty string. To get current text in a ComboBox when it does not have focus, use Text property.

DataSource

A ComboBox can be used to bind to a collection of items. DataSource property is used to get and set a data source to a ComboBox. The data source can be a collection or object that implements IList interface such as an array, a collection, or a DataSet.

The following code snippet binds an enumeration converted to an array to a ComboBox.

  1. comboBox1.DataSource = System.Enum.GetValues(typeof(ComboBoxStyle));  

DropDownStyle

DropDownStyle property is used to gets and sets the style of a ComboBox. It is a type of ComboBoxStyle enumeration.

The ComboBoxStyle enumeration has following three values.

  • Simple — List is always visible and the text portion is editable.
  • DropDown – List is displayed by clicking the down arrow and that the text portion is editable.
  • DropDownList — List is displayed by clicking the down arrow and that the text portion is not editable.

The following code snippet sets the DropDownStyle property of a ComboBox to DropDownList. 

  1. comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;  

DroppedDown

If set true, the dropped down portion of the ComboBox is displayed. By default, this value is false.

Sorting Items

The Sorted property set to true, the ComboBox items are sorted. The following code snippet sorts the ComboBox items.

  1. comboBox1.Sorted = true;  

Find Items

FindString method is used to find a string or substring in a ComboBox. The following code snippet finds a string in a ComboBox and selects it if found.

  1. private void FindButton_Click(object sender, EventArgs e)  
  2. {  
  3.    int index = comboBox1.FindString(textBox1.Text);  
  4.    if (index < 0)  
  5.    {  
  6.       MessageBox.Show(«Item not found.»);  
  7.       textBox1.Text = String.Empty;  
  8.    }  
  9.    else  
  10.    {  
  11.       comboBox1.SelectedIndex = index;  
  12.    }  
  13. }  

ComboBox SelectedIndexChanged Event Hander


CheckedChanged and CheckStateChanged are two important events for a ComboBox control. The CheckedChanged event occurs when the value of the Checked property changes. The CheckStateChanged event occurs when the value of the CheckState property changes.

To add these event handlers, you go to Events window and double click on CheckedChanged and CheckedStateChanged events as you can see in Figure 8.

ComboBox In C#

Figure 8

The following code snippet defines and implements these events and their respective event handlers.

  1. comboBox1.SelectedIndexChanged += new System.EventHandler(ComboBox1_SelectedIndexChanged);  
  2. private void ComboBox1_SelectedIndexChanged(object sender,  
  3. System.EventArgs e)  
  4. {  
  5.    MessageBox.Show(comboBox1.Text);  
  6. }  

Summary

In this article, we discussed discuss how to create a ComboBox control in Windows Forms at design-time as well as run-time. After that, we discussed how to use its various properties and methods to build real world applications.

Понравилась статья? Поделить с друзьями:
  • Windows forms c решение квадратного уравнения
  • Windows forms c возведение в степень
  • Windows forms c visual studio учебник
  • Windows forms c visual studio 2019 уроки
  • Windows forms c visual studio 2010 скачать