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:
use
find()
method ofbindingsource
://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.
use little trick
findstringexact()
method ofcombobox
: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
Post a Comment