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!
Asked
Active
Viewed 1.9k times
1 Answers
33
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;

Adi Kusuma
- 45
- 1
- 5

J J
- 1,550
- 4
- 17
- 27
-
Wow that's cool, I did it a little differently, but the idea is the same, thanks a ton! – sooprise Sep 21 '10 at 18:14
-
Basically, cast is to ComboBoxItem, and then get the hidden value... ((ComboBoxItem)ComboBox.SelectedItem).hiddenValue; Assuming that hiddenValue was public. You'd usually create an accessor for the property instead. – J J Sep 21 '10 at 18:25
-
Added the accessor and comments. – J J Sep 21 '10 at 22:05
-
1Thanks @JJ... Man, you saved my time, and unnecessary codings! – don Nov 08 '12 at 10:48
-
is it possible to set the item based on the hidden value? for example combobox.selecteditem = combobox.hiddenvalue(123) – sharkyenergy Feb 19 '17 at 20:42