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!
A:
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;
J J
2010-09-21 18:04:03
Wow that's cool, I did it a little differently, but the idea is the same, thanks a ton!
Soo
2010-09-21 18:14:51
Ok wait, now how to I get the hidden value? ComboBox.SelectedItem.???
Soo
2010-09-21 18:17:07
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
2010-09-21 18:25:07
Can you add an accessor to the above code example?
Soo
2010-09-21 18:29:58
Added the accessor and comments.
J J
2010-09-21 22:05:51