User13839404
User13839404

Reputation: 1813

How to get value from combobox in c#?

I can't get value from ComboBox in WinForms using C#.

I have a ComboBox populated with a list of values and I have set ValueMember and DisplayMember.

Now, I have to find the value of the selected ComboBox item and select the matched item in UI.

Here is what I mean:-

I loaded the ComboBox like this :-

var list = (from l in db.Loc
            orderby l.LName ascending
            select l).ToList();
list.Insert(0, new Loc { ID = "-1", Name = "--Select--" });
cmb1.BindingContext = new BindingContext();
cmb1.DataSource = list;
cmb1.DisplayMember = "Name";
cmb1.ValueMember = "ID";

Now on an event, I am trying to match value (ID) and select the item. It's easy if I match Text property:

cmb1.Text = data.Name;

But How to match the value?

Something like this:-

cmb1.Value = data.ID;

Upvotes: 1

Views: 17048

Answers (6)

Akram Shahda
Akram Shahda

Reputation: 14771

First of all: cmb1.Text = text; changes the text of the ComboBox to the specified value. It doesn't select the item with the text that matchs the specified value.

Use cmb1.SelectedValue = value; to select the item with the speciefied value.

Upvotes: 1

WraithNath
WraithNath

Reputation: 18013

If you only know the ID of the item you can also use:

cmb1.SelectedValue = data.ID;

Upvotes: 3

manji
manji

Reputation: 47968

data must be in the list binded to the combobox, then:

cmb1.SelectedItem = data

or, if it's not (you retrieved another instance from somewhere):

cmb1.SelectedValue = data.ID

Upvotes: 1

Alexander Galkin
Alexander Galkin

Reputation: 12524

Why would you like to assign you "matched" value to the ComboBox Value property? As soon as you have correctly set DisplayMember and ValueMember and you DataSource implements both as properties the values will be autoamatically "matched", e.g. you can read the Value property in you event handler to get this "matched" value.

Upvotes: 1

Homam
Homam

Reputation: 23841

This should work:

cmb1.SelectedValue = data.ID;

Upvotes: 2

Anuraj
Anuraj

Reputation: 19598

You can get the index using Combo1.SelectedIndex property. You can get the item using either Combo1.SelectedItem or Combo1.Items[Combo1.SelectedIndex]

Upvotes: 0

Related Questions