ComboBox
This useful control is a combination TextBox
with a drop-down. The user can type anything into the ComboBox
, or select something from the list.
Please create a new Windows Forms application and add a ComboBox
to it. You can then right-click on the ComboBox
and add event handlers.
Ensure the SelectedIndexChanged
and TextChanged
event handlers were added. We can add code directly to handle changes in the ComboBox
.
ComboBox
or by clicking on the list of Items, the event handlers are triggered.ComboBox
.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); } } }
On a ComboBox
, 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.
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"; } } }
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.
string
variables to it. To clear it, you can assign it to an empty string
.ComboBox
combines a TextBox
and a drop-down list. It is ideal for dialogs where some suggestions for an input may be known, but any value must be accepted.