Выпадающий список windows form

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

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

Подобным образом, как и с ListBox, мы можем в окне свойств на свойство Items и нам отобразится окно для добавления элементов 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.

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.

comboBox1.Location = new System.Drawing.Point(20, 60);
comboBox1.Name = "comboBox1";
comboBox1.Size = new System.Drawing.Size(245, 25);
comboBox1.BackColor = System.Drawing.Color.Orange;  
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.

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.

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.

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

DropDownHeight and DropDownWidth

You 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.

comboBox1.DropDownHeight = 50;  
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.

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.

comboBox1.BackColor = System.Drawing.Color.Orange;  
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.

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. 

comboBox1.Items.Add("Mahesh Chand");  
comboBox1.Items.Add("Mike Gold");  
comboBox1.Items.Add("Praveen Kumar");  
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.

private void GetItemsButton_Click(object sender, EventArgs e)  
{  
    StringBuilder sb = new StringBuilder();  
    foreach (string name in Combo1.Items)  
    {  
        sb.Append(name);  
        sb.Append(" ");  
    }  
    MessageBox.Show(sb.ToString());  
}

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.

comboBox1.Text = "Mahesh Chand";  
MessageBox.Show(comboBox1.Text);

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

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.

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. 

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. 

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.

private void FindButton_Click(object sender, EventArgs e)  
{  
   int index = comboBox1.FindString(textBox1.Text);  
   if (index < 0)  
   {  
      MessageBox.Show("Item not found.");  
      textBox1.Text = String.Empty;  
   }  
   else  
   {  
      comboBox1.SelectedIndex = index;  
   }  
}

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.

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

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.

This C# article demonstrates the ComboBox control. It covers ComboBox properties and event handlers.

ComboBox is a combination TextBox with a drop-down. Its drop-down list presents preset choices.

The user can type anything into the ComboBox. Alternatively, he or she can select something from the list.

TextBox

Example. To begin, please create a new Windows Forms application and add a ComboBox to it. You can then right-click on the ComboBox and add the SelectedIndexChanged and TextChanged event handlers in the Properties dialog.

This program shows how when you change the text by typing in the ComboBox or by clicking on the list of Items, the event handlers are triggered. Please see the section on the Items property before running the program.

C# program that demonstrates ComboBox event handlers

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
	public Form1()
	{
	    InitializeComponent();
	}

	int _selectedIndex;
	string _text;

	private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
	{
	    // Called when a new index is selected.
	    _selectedIndex = comboBox1.SelectedIndex;
	    Display();
	}

	private void comboBox1_TextChanged(object sender, EventArgs e)
	{
	    // Called whenever text changes.
	    _text = comboBox1.Text;
	    Display();
	}

	void Display()
	{
	    this.Text = string.Format("Text: {0}; SelectedIndex: {1}",
		_text,
		_selectedIndex);
	}
    }
}

Text. The Text property of the ComboBox functions much like the Text property of a TextBox. If you assign to the Text property, the current value in the ComboBox will change. You can also read the Text property and assign string variables to it.

Tip: To clear it, you can assign it to an empty string literal. This is an effective way to clear many properties.

Empty String ExamplesString Literal

Items. The Items property contains the strings that are found in the drop-down part of the ComboBox. You can type the Items line-by-line into Visual Studio through the Items dialog, or you can dynamically add them during runtime.

Tip: To add Items, call the Add method: use the syntax comboBox1.Add(«Value»). You can also Clear the ComboBox with Clear().

Dialog usage. Conceptually, the ComboBox is used to represent a text input with a set of associated, predefined values that are easy to select. For this reason, it is a good choice for preference dialogs.

You can use ComboBox controls and have preset values that are present in the drop-downs, but allow your users to select any value by typing it in directly. This avoids the need for more than one control.

AutoComplete. There are three properties for AutoComplete on the ComboBox: the AutoCompleteCustomSource, the AutoCompleteMode, and the AutoCompleteSource. The AutoCompleteMode property can be set to suggest, append or both.

And: Source properties let you specify the set of strings that are used as suggestions.

DropDown styles. There are three DropDown style properties. They are DropDownHeight, DropDownStyle and DropDownWidth. The DropDownHeight and DropDownWidth properties seem not to affect the visual appearance. Windows uses its default widgets.

Also: You can remove the drop-down entirely (with Simple), or make it so the text is not editable (with DropDownList).

MaxDropDownItems. The MaxDropDownItems property had no effect in my testing. In a ComboBox with three items, setting a MaxDropDownItems of one did not reduce the number of items. It may be effective only when DropDownStyle is set to a non-default value.

Summary. By combining the TextBox and a regular drop-down list, the ComboBox control represents a truly useful hybrid widget in Windows Forms. It is ideal for dialogs where some suggestions for an input may be known, but any value must be accepted.

Review: The ComboBox can streamline your interface by coalescing multiple user interface controls.


Related Links

Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf

You currently have JavaScript disabled on your web browser.

This website uses JavaScript, and This web page needs JavaScript activated to work correctly.

Please active JavaScript on your web browser and then refresh this web page.

ComboBox

By Tim-Bo Tolbert, posted on Dec 26, 2021

The ComboBox control is found in the System.Windows.Forms namespace within the System.Windows.Forms.dll. In this blog post I am referring to the ComboBox control that is available in C# .NET-Core (.NET 6.0) with Visual Studio 2022 (although this code example might still work OK with older .NET versions).

The purpose and function of the ComboBox is to display a text box combined with a ListBox, which enables the user to select items from its drop down list or enter a new value into its text box.

You can change the way the ComboBox control looks on the form by altering the DropDownStyle property, so that its list is either always displayed or displayed in a drop-down. The DropDownStyle property also specifies whether the text portion is ReadOnly or if it can be edited. There is no setting to always display the list and disallow entering a new value (which is what a ListBox control is).

Items can be added or removed to the ComboBox control both at design time and at run time. You can assign an array of object references to add a group of items at once by using the AddRange method, which then displays the default string value for each object. You can add individual objects with the Add method. With the BeginUpdate and EndUpdate methods, you can add a large number of items without the control being repainted each time an item is added to the list. You can delete items with the Remove method, or you can clear all items from the entire list with the Clear method.

The ComboBox also provides features that enable you to efficiently add items and find text within the items of the list. The FindString and FindStringExact methods enable you to search for an item in the list that contains a specific search string.

Example Source Code

This example uses a ComboBox control, along with two Label controls and a TextBox control.

To add the ComboBox control to your form, you can double click on its name (i.e. ComboBox) as listed in the Toolbox window panel within the Form editor window. Alternatively, you can single click on it and then drag and drop it onto your form, to position it more closer to where you want it to be positioned at. Once it is added to the form then it will appear on the forms surface area having default ComboBox control values.

After you have added the ComboBox control to your form, then once you select it then you can view and edit that objects property values in the Properties window within the Forms editor window, where you can then change the controls Name, Items, and other properties as you desire.

In the following example, I added two Label objects to the Form, and then changed one of the Labels Text property to have a value of «Favorite Pet:» and the other Labels Text property to have a value of «Info:». I then added a ComboBox and positioned it be next to the first Label, and then added a TextBox and positioned it below the second Label. I adjusted the TextBox properties so that it is MultiLined, ReadOnly, and Scrollbars Visible:

example2

From the Form editor, I select the control, view its Events properties in the Property Window, and then double clicked on the SelectedValueChanged and on the TextChanged events. Doing so automatically creates and links callback methods to that controls event into that forms .cs source code file, which I can then program some action to be performed whenever the user changes the value. In this example I use both events so that one captures when the user selects something from its drop down list and the other captures when the user manually types or pastes some value in. I then have both callback methods call and use the same function to process the selected item and then give some feedback to the user in the TextBox control:

namespace TestProgram
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // add items to the combo box
            comboBox1.Items.AddRange(new object[] {
            "Cat",
            "Dog",
            "Bird",
            "Fish"});
        }

        private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            // the user selected a drop down value so process it
            processSelection();
        }

        private void comboBox1_TextChanged(object sender, EventArgs e)
        {
            // the user manually entered a value so process it
            processSelection();
        }

        // custom function to process the combobox text
        private void processSelection()
        {
            // get the current text
            string tempText = comboBox1.Text.Trim().ToLower();
            
            // check if it is one of the items
            if (tempText == "")
            {
                textBox1.Text = "";
            }
            else if (tempText == "cat")
            {
                textBox1.Text = "Cats are small carnivorous mammals. The scientific name for Cat is Felis catus.";
            }
            else if (tempText == "dog")
            {
                textBox1.Text = "Dogs are descendants of the wolf.";
            }
            else if (tempText == "bird")
            {
                textBox1.Text = "There are over 10,000 different species of birds around the world.";
            }
            else if (tempText == "fish")
            {
                textBox1.Text = "The whale shark is the largest fish, measuring over 18 meters in length.";
            }
            else
            {
                textBox1.Text = "Your favorite pet is a " + comboBox1.Text;
            }
        }
    }
}

When you run the above examples and either select something from the ComboBox’s drop down list or type something into the ComboBox’s text box then you should see something similar to the following:


Final Thoughts

Thank you for reading, I hope you found this blog post (tutorial) educational and helpful.

This page has been viewed a total of 2526 times.

Visual Studio C#: обзор ComboBox


Добавил(а) microsin

  

Элемент управления System.Windows.Forms.ComboBox позволяет запомнить в себе список текстовых элементов, и предоставить выбор одного из элементов для пользователя.

Неочевидно, что основное поведение ComboBox зависит от свойства DropDownStyle. Имеется 3 варианта на выбор:

Элементы в списке программно доступны через свойство ComboBox.Items. Количество элементов в списке можно получить через ComboBox.Items.Count. Добавлять элементы можно методом ComboBox.Items.Add, удалять методами Remove и RemoveAt. Текущий отображаемый элемент Items можно программно поменять через значение свойства SelectedIndex.

[Ответы на часто задаваемые вопросы по ComboBox (FAQ)]

Q01. Как запретить (отключить) редактирование элемента в окне ComboBox?
A01. Поменяйте свойство DropDownStyle на DropDownList.

Q02. Как разрешить редактирование элемента в окне ComboBox?
A02. Поменяйте свойство DropDownStyle на DropDown. Это поведение ComboBox по умолчанию.

Q03. При запуске программы в окне ComboBox не отображен ни один элемент. Как сделать, чтобы был виден/выбран нужный элемент из списка Items?
A03. Присвойте свойству SelectedIndex нужное значение, соответствующее номеру элемента в списке Items. Элементы нумеруются начиная с нуля. Например, чтобы отобразить первый элемент в списке, нужно SelectedIndex присвоить значение 0.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • C programdata microsoft windows wfp wfpdiag etl
  • Курсы по системному администрированию windows
  • Fbreader for windows что за программа
  • Game bar windows 10 не записывает звук
  • Как переустановить windows на lenovo b50 30