Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hidden Id With ComboBox Items?

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!

like image 698
sooprise Avatar asked Sep 21 '10 17:09

sooprise


1 Answers

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;
like image 184
J J Avatar answered Oct 17 '22 01:10

J J