How to use ComboBox in C#

By FoxLearn 7/16/2024 8:35:51 AM   7.12K
In C#, a ComboBox is a commonly used control in Windows Forms applications for presenting a dropdown list of items to users, allowing them to select one or more options from the list.

How to use Combobox control in C#

Open your Visual Studio, then click New Project. Select Visual C# on the left, then Windows and then select Windows Forms Application. Enter name your project, then click OK button.

Next, Open your form designer, then drag and drop a ComboBox control onto the Form from the Visual Studio toolbox.

c# combobox

Here's a basic example of how to create and use a ComboBox in C#

This is just a basic c# example. I'll show you how to add item or binding item to combobox, then get selected item from combobox in C#.

I'll create a State class to map data

public class States
{
    public string ID { get; set; }
    public string Name { get; set; }
}

Select the state combobox, then add a SelectedIndexChanged event handler.

// ComboBox C# Winform
private void cboState_SelectedIndexChanged(object sender, EventArgs e)
{
    lblValue.Text = cboState.Text;
}

You can subscribe to the SelectedIndexChanged event to handle changes in selection.

When the selection changes, the cboState_SelectedIndexChanged event handler is triggered, setting the value to label control with the selected item's text.

Double click to your form to add a Form_Load event handler that allows you to initialize data for the combobox control.

// ComboBox DataSource C#
private void Form1_Load(object sender, EventArgs e)
{
    //Add item to combobox
    cboState.Items.Add("Arizona");
    cboState.Items.Add("Ohio");
    cboState.SelectedIndex = 1;
    //Clear all item cboState2
    cboState2.Items.Clear();
    //Init data
    List<States> list = new List<States>();
    list.Add(new States() { ID = "01", Name = "Texas" });
    list.Add(new States() { ID = "02", Name = "Ohio" });
    list.Add(new States() { ID = "02", Name = "Utah" });
    list.Add(new States() { ID = "04", Name = "Vermont" });
    //Set display member and value member for combobox
    cboState2.DataSource = list;
    cboState2.ValueMember = "ID";
    cboState2.DisplayMember = "Name";
}

You can set the default selection using the SelectedIndex property.

Select the state2 combobox, then add a SelectionChangeCommitted event handler that allows you to update text to the label control.

// C# ComboBox text change event
private void cboState2_SelectionChangeCommitted(object sender, EventArgs e)
{
    //Cast item to State object
    States obj = cboState2.SelectedItem as States;
    if (obj != null)
        lblValue.Text = obj.Name;
}

ComboBoxes offer various properties and events for customization and interaction, such as DropDownStyle, DropDownWidth, DropDownHeight, SelectedItem, SelectedIndex, TextChanged, etc. You can explore these properties and events to tailor the ComboBox behavior to your application's needs.

VIDEO TUTORIALS