6

I have a combobox with the following structure. Also, I am getting a fld_id from another source and based on that id I need to select the corresponding item in the ComboBox. How can I do that?

comboBoxCustomers.DataSource = customers;

comboBoxCustomers.ValueMember = "fld_id";

comboBoxCustomers.DisplayMember = "fld_name";

Example:

List could contain these items

fld_id   fld_name

65       Item1

68       Item2

69       Item3

I need to set Item 68 as selected.

Ironcache
  • 1,719
  • 21
  • 33
Alexandru Pupsa
  • 1,798
  • 4
  • 21
  • 40
  • What do you meany by *I am getting a fld_id from another source and based on that id I need to select the corresponding item in the ComboBox*? Post some more code to show how you get `fld_id`? Is that a property? – Sriram Sakthivel Aug 04 '14 at 09:07
  • It doesn't matter where it comes from. I just need to select the item with that id as valuemember – Alexandru Pupsa Aug 04 '14 at 09:10
  • what happens when you: `var selected = comboBoxCustomers.SelectedValue;` ? – Apostrofix Aug 04 '14 at 09:13
  • Actually, it matters! If it is a property you can use [binding to bind it as shown here](http://stackoverflow.com/a/25030968/2530848). Though am not sure whether it will work in this scenario. – Sriram Sakthivel Aug 04 '14 at 09:14
  • @Apostrofix NO! I need to set it as selected. There is nothing selected. I am building the ComboBox – Alexandru Pupsa Aug 04 '14 at 09:14
  • 1
    try this : comboBoxCustomers.SelectedValue = 68; – Pranav1688 Aug 04 '14 at 09:15
  • okay, so if i understood you correctly, this should help you: http://stackoverflow.com/questions/2864065/c-sharp-set-combo-item-with-selectedvalue – Apostrofix Aug 04 '14 at 09:19

4 Answers4

8

Use Following:

comboBoxCustomers.SelectedValue = fld_id(which you are getitng from another source)
Tithi Patel
  • 777
  • 4
  • 21
8

I don't have enough reputation to post a comment. This:

comboBoxCustomers.SelectedValue = fld_id

works great :) But AFTER showing the form, otherwise it will fail.

LuisEduardoSP
  • 401
  • 5
  • 11
0

if you use datasource of the combobox, you can cast the datasource back to the list, find the item and use that item to set the selected item:

var stores = cbxStores.DataSource as List<store>;
var store = stores.Where(w => w.store_code == _station.store_code).FirstOrDefault();
cbxStores.SelectedItem = store;
Jan Feyen
  • 535
  • 3
  • 13
0

Simplest procdure I found for myself:

You can bind it into some function with perameters while funtion is called.

Hope it is going to help you guys:

int Idd = Convert.ToInt32(your value for the combobox  you want to be selected);
for (int i = 0; i < myComboBox.Items.Count; i++)
{
    myComboBox.SelectedIndex = i;
    if (Convert.ToInt32( myComboBox.SelectedValue ) == Idd )
        {break;}                   
}
baitmbarek
  • 2,440
  • 4
  • 18
  • 26