I have this form, in which i need to populate a combo box with a text-value pair from the database, so that i can use the value in an update query to the database
i found some method that uses a class to make objects which have both text and a value as:
class RequestType
{
public string Text { get; set; }
public string Value { get; set; }
public RequestType(string text, string val)
{
Text = text;
Value = val;
}
public override string ToString()
{
return Text;
}
and i added them to the combo box like this
RequestType type1 = new RequestType("Label 1", "Value 1");
RequestType type2 = new RequestType("Label 2", "Value 2");
comboBox1.Items.Add(type1);
comboBox1.Items.Add(type2);
comboBox1.SelectedItem = type2;
now i don’t know how to retrieve the value of the selected item, i.e. id label 1 is selected, it must return value1 and if label 2 is selected, it returns value2,
any help please??? thanxx in advance
The Items collection of a combobox is of type ObjectCollection, so when you set an item with
you are adding a RequestType object to the collection.
Now, when you want to retrieve a single selected item from that collection, you could use a syntax like this
Theoretically, (when you have complete control on the adding of the combobox items) you could avoid to check if the conversion applied with the
askeyword was successful, but this is not the case because the SelectedItem could be null and therefore it is always a good practice to test with