views:

65

answers:

1

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
Wow that's cool, I did it a little differently, but the idea is the same, thanks a ton!
Soo
Ok wait, now how to I get the hidden value? ComboBox.SelectedItem.???
Soo
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
Can you add an accessor to the above code example?
Soo
Added the accessor and comments.
J J