Skip to main content
Mar 03, 2015

Combobox is a C# class that displays values in a dropdown list. Usually, it keeps simple string data only, but often we need to know an  identificator of selected string value.

This article contains information how to add values with Id to combobox in C#. The trick is to use a class with properties, Id and Name and to add an instance of the class as the combobox item.

Class to be used as container for id and value:

///
/// Class for keeping atribute value and id in combobox
///
class ComboboxValue
{
  public int Id { get; private set; }
  public string Name { get; private set; }
 
  public ComboboxValue(int id, string name)
  {
    Id = id;
    Name = name;
  }
 
  public override string ToString()
  {
    return Name;
  }
}

How to use the class in the code for inserting value with id into combobox and getting from it:

...
// Create combobox
Combobox cb = new Combobox();
...
// Add class to combobox items
cb.Items.Add(new ComboboxValue(10, "Example value"));
...
// Get values from selected checkbox item
ComboboxValue tmpComboboxValue = (ComboboxValue)cb.SelectedItem;
...