Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Alias value for Combobox items

Status
Not open for further replies.

golcarlad

Programmer
Nov 23, 2004
232
GB
Is there a way for a combobox item to have an "alias" value e.g. if you select from colours combobox - RED, then you can return a value of 987, or BLUE would return 876 - whatever.
Bearing in mind you cant use Tag property when pre-popping a combobox at design time.
Or is this a case for custom controls?
 
ComboBoxes are a bit dumb.

Create a hashtable that uses the combobox index as key, and your "alias" as the value. Just remember to clear this hash table whenever you clear your combobox

:)
 
Cheers guys - its nice to know that comboboxes are dumb afterall, I always kept trying to make them do stuff, I they just dont want to play! lol
 
ComboBoxes are not dumb.. and you dont need any hash tables to have more data on them.

As you might have already noticed, ComboBox.Items.Add requires an object variable, NOT just a string. This means you can add actual objects to the list, whose structure is up to you. Just dont forget to set ComboBox.DisplayMember and ComboBox.ValueMember (if needed) to the names of corresponding object's properties.

Example:

Code:
class MyOwnListItem
{
   private string text;
   private int value;

   public string Text { get { return text; } }
   public int Value { get { return value; } }

   public MyOwnListItem(string newText, int newValue)
   {
      text = newText;
      value = newValue;
   }
}

class MyForm
{
   // .........
   protected void FillComboBox()
   {
       myCombo.DisplayMember = "Text";
       myCombo.ValueMember = "Value";
       myCombo.Items.Add(new MyOwnListItem("One", 1));
       myCombo.Items.Add(new MyOwnListItem("Two", 2));
   }

   protected void AccessComboBox()
   {
      string selText = myCombo.SelectedText;
      int selValue = (int) myCombo.SelectedValue;
      MyOwnListItem selItem = (MyOwnListItem) myCombo.SelectedItem;
   }
}

good luck ;)

------------------
When you do it, do it right.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top