Question

The DataSource of comboBox is a DataTable. The DataTable has a key column called ID, the values of IDs can be 1,2,3,4,5.

I want to set the SelectedIndex of comboBox correspondingly to the ID I want. Here is my try, it works OK but I'm not sure it's the best:

DataTable source = (DataTable) myComboBox.DataSource;
DataRow[] rows = source.Select(string.Format("ID='{0}'", 3));//the ID I want is 3
myComboBox.SelectedIndex = rows.Length == 0 ? -1 : source.Rows.IndexOf(rows[0]);

Do you have another better solution?

Thanks a lot!

Was it helpful?

Solution

I've tried myself, but I'm not sure if they are better than the one I posted in my original question. Here they are:

  1. Use the Find() method of BindingSource:

    //Only 1 line of code, seems to much cleaner :)
    myComboBox.SelectedIndex = new BindingSource(myComboBox.DataSource,"").Find("ID",3);
    //In fact, I thought of this before but I had tried the solution in my OP first.
    
  2. Use a little trick with FindStringExact() method of ComboBox:

    string currentDisplayMember = myComboBox.DisplayMember;
    myComboBox.DisplayMember = "ID";
    myComboBox.SelectedIndex = myComboBox.FindStringExact("3");
    myComboBox.DisplayMember = currentDisplayMember;
    

The #2 should be used carefully if you have something related to DisplayMember to handle when the SelectedIndexChanged is fired.

I hope this helps others. Please leave your comment below if they're better than the method I used in my original question. Thanks!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top