c# - Set SelectedIndex of combobox to an index found by a key value in the underlying DataSource? -


the datasource of combobox datatable. datatable has key column called id, values of ids can 1,2,3,4,5.

i want set selectedindex of combobox correspondingly id want. here try, works ok i'm not sure it's best:

datatable source = (datatable) mycombobox.datasource; datarow[] rows = source.select(string.format("id='{0}'", 3));//the id want 3 mycombobox.selectedindex = rows.length == 0 ? -1 : source.rows.indexof(rows[0]); 

do have better solution?

thanks lot!

i've tried myself, i'm not sure if better 1 posted in original question. here are:

  1. use find() method of bindingsource:

    //only 1 line of code, seems cleaner :) mycombobox.selectedindex = new bindingsource(mycombobox.datasource,"").find("id",3); //in fact, thought of before had tried solution in op first. 
  2. use little trick findstringexact() method of combobox:

    string currentdisplaymember = mycombobox.displaymember; mycombobox.displaymember = "id"; mycombobox.selectedindex = mycombobox.findstringexact("3"); mycombobox.displaymember = currentdisplaymember; 

the #2 should used if have related displaymember handle when selectedindexchanged fired.

i hope helps others. please leave comment below if they're better method used in original question. thanks!


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -