Since FrameWork 1.1, the ComboBox Control exposes DisplayMember, and ValueMember, Properties which you can use with a DataSource to handle exactly the type of problem you describe here. MS has a complete example here:[
^].
Another, simpler, technique you can use is to create a generic Dictionary of the form:
private Dictionary<int,> dctComboXRef = new Dictionary<int,>
{
{0, "hallo"},
{1, "goodbye"},
{2, "whatever"}
};
private void YourForm_Load(object sender, EventArgs e)
{
foreach (var kvp in dctComboXRef)
{
comboBox1.Items.Add(kvp.Key);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedAsString = dctComboXRef[comboBox1.SelectedIndex];
Console.WriteLine("selected " + selectedAsString);
}
Why did I use integers as the key in the Dictionary, rather than a string ? Because a ComboBoxItems collection is, by definition, a list which guarantees every Item has a unique index, and a Dictionary must have unique indexes, and because it's so simple to fetch the string from the Dictionary using the integer index of the Item selected.
The two techniques mentioned above are not the only ways (besides Reflection) you could handle the task of cross-referencing a string based on the selection in a ComboBox.
experiment + observe + analyze + study == competence :)