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 biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

populating a combobox on a windows application

Status
Not open for further replies.

plork123

Programmer
Mar 8, 2004
121
GB
I tring with frustration to populate a combo box in c# but not using a database

e.g. combobox displays
red
white
blue

But want i want is if a person chooses red i want to pass back the number 1 value to another method

i'm able to populate a combo box with the colours but not sure how i 'grab' the value to pass back

string[] colours = new string[] { "red", "white", "blue" };
m_cmbColours.Items.AddRange(colours);

What i want is this
value colour
1 red
2 white
3 blue

combo box just displays the colours and when chosen in the combo box i grab the value corresponding to colour chosen

any help much appreciated
 
If you add them in that order, then you can get the SelectedIndex + 1

However, you will want to take a look at Enums. An enum is a label for a number essentially. This way you know what 1 is and you know what 2 is...


public enum ColorValue
{
RED = 0, WHITE = 2, BLUE = 3
}

Now you could use it like this:

public void DoSomething(ColorValue c)
{
switch (c)
{
ColorValue.RED:
{
}
ColorValue.BLUE:
{
}
ColorValue.WHITE:
{
}
}
}

 

Thanks for the help

Is there a way to use this method but instead of an integer i pass a string value?



 
Use the enum method - and simply add a Dictionary<> or HashTable with integer/enum keys and string values.

Dictionary<ColorValue, string> colorcodes = new Dictionary<ColorValue, string>();

colorcodes.Add(ColorValue.RED, "#FF0000");
colorcodes.Add(ColorValue.BLUE, "#3333CC");
colorcodes.Add(ColorValue.WHITE, "#FFFFFF");


string webcolor = colorcodes[ColorValue.RED];


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top