C# ComboBox: Windows FormsUse the ComboBox control and its properties and event handlers.
ComboBox. This useful control is a combination TextBox with a drop-down. Its drop-down list presents preset choices. The user can type anything into the ComboBox, or select something from the list.
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.
Program When you change the text by typing in the ComboBox or by clicking on the list of Items, the event handlers are triggered.
Items Please see the section on the Items property before running the program. With Items we add strings to the ComboBox.
Add, assign items. Once a ComboBox has been added to a Windows Form, we can call Add() on its Items to add entries. Then we can assign them by index once they are added. We can adjust Items dynamically.
Tip You can type the Items line-by-line into Visual Studio through the Items dialog, or you can dynamically add them during runtime.
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.
C# program that adds and assigns items
using System; using System.Windows.Forms; namespace WindowsFormsApp2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Add items. comboBox1.Items.Add("bird"); comboBox1.Items.Add("frog"); // Can assign items if they already exist. comboBox1.Items[0] = "dog"; } } }
Summary. The ComboBox control combines the TextBox and a drop-down list. It represents a 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.
© 2007-2021 sam allen.
see site info on the changelog.