C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
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);
}
}
}
Tip: To clear it, you can assign it to an empty string literal. This is an effective way to clear many properties.
Empty StringString LiteralTip: To add Items, call the Add method: use the syntax comboBox1.Add("Value"). You can also Clear the ComboBox with Clear().
And: Source properties let you specify the set of strings that are used as suggestions.
Also: You can remove the drop-down entirely (with Simple), or make it so the text is not editable (with DropDownList).
Note: Thanks to Clarence Ravel for showing that MaxDropDownItems has an effect for a false IntegralHeight.
Review: The ComboBox can streamline your interface by merging user interface controls.