![](/img/trans.png)
[英]Is it possible to set the selectedIndex of a combobox based on its value
[英]Set SelectedIndex of combobox to an index found by a key value in the underlying DataSource?
comboBox的数据源是一个数据表。 DataTable有一个称为ID的键列,ID的值可以为1,2,3,4,5。
我想根据我想要的ID设置comboBox的SelectedIndex。 这是我的尝试,它可以正常工作,但我不确定这是最好的方法:
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]);
您还有其他更好的解决方案吗?
非常感谢!
我已经尝试过了,但是我不确定它们是否比我在原始问题中发布的要好。 他们来了:
使用BindingSource
的Find()
方法:
//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.
对ComboBox
FindStringExact()
方法使用一些技巧:
string currentDisplayMember = myComboBox.DisplayMember; myComboBox.DisplayMember = "ID"; myComboBox.SelectedIndex = myComboBox.FindStringExact("3"); myComboBox.DisplayMember = currentDisplayMember;
如果在启动SelectedIndexChanged
时有一些与DisplayMember
相关的内容要处理,则应谨慎使用#2。
我希望这对其他人有帮助。 如果它们比我在原始问题中使用的方法更好,请在下面留下您的评论。 谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.