I know how to add items to a ComboBox, but is there anyway to assign a unique Id to each item? I want to be able to know which Id is associated to each item if it is ever selected. Thanks!
The items in a combobox can be of any object type, and the value that gets displayed is the ToString() value.
So you could create a new class that has a string value for display purposes and a hidden id. Simply override the ToString function to return the display string.
For instance:
public class ComboBoxItem
{
   string displayValue;
   string hiddenValue;
   // Constructor
   public ComboBoxItem (string d, string h)
   {
        displayValue = d;
        hiddenValue = h;
   }
   // Accessor
   public string HiddenValue
   {
        get
        {
             return hiddenValue;
        }
   }
   // Override ToString method
   public override string ToString()
   {
        return displayValue;
   }
}
And then in your code:
// Add item to ComboBox:
ComboBox.Items.Add(new ComboBoxItem("DisplayValue", "HiddenValue");
// Get hidden value of selected item:
string hValue = ((ComboBoxItem)ComboBox.SelectedItem).HiddenValue;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With