Samy S.Rathore
Samy S.Rathore

Reputation: 1823

how to retrieve the value of the value-tem pair in a combo box in c#.net?

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

Upvotes: 0

Views: 170

Answers (4)

Steve
Steve

Reputation: 216342

The Items collection of a combobox is of type ObjectCollection, so when you set an item with

comboBox1.Items.Add(type1); 

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

RequestType t = comboBox1.SelectedItem as RequestType;

Theoretically, (when you have complete control on the adding of the combobox items) you could avoid to check if the conversion applied with the as keyword 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

   if(t != null)
   {
       Console.WriteLine(t.Value + " " + t.Text);
   }

Upvotes: 0

Marco
Marco

Reputation: 57593

I think you could use:

if (combobox1.SelectedItem != null)
    val2 = (comboBox1.SelectedItem as RequestType).Value;

or

string val2 = combobox1.SelectedItem != null ?
                  (comboBox1.SelectedItem as RequestType).Value :
                  null;

Upvotes: 0

Maarten
Maarten

Reputation: 22955

You can cast the comboBox1.SelectedItem to your type, RequestType, and then you can read its properties.

Upvotes: 0

Prateek Singh
Prateek Singh

Reputation: 863

RequestType type = (RequestType)comboBox1.SelectedItem;

Now, Value of the selected item = type.Value

Upvotes: 0

Related Questions