This page was last reviewed on Sep 29, 2022.
Dot Net Perls
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.
Getting started. 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.
Example code. Ensure the SelectedIndexChanged and TextChanged event handlers were added. We can add code directly to handle changes in the ComboBox.
Detail When you change the text by typing in the ComboBox or by clicking on the list of Items, the event handlers are triggered.
Detail Please see the section on the Items property before running the program. With Items we add strings to the 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); } } }
Add example. 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.
Tip You can type the Items line-by-line into Visual Studio through the Items dialog, or you can dynamically add them during runtime.
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"; } } }
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.
Also You can read the Text property and assign string variables to it. To clear it, you can assign it to an empty string.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 29, 2022 (edit).
Home
Changes
© 2007-2024 Sam Allen.