将组合框的SelectedIndex设置为根据基础数据源中的键值找到的索引

本文关键字:数据源 键值 索引 组合 SelectedIndex 设置 | 更新日期: 2023-09-27 18:13:29

comboBox的数据源是一个数据表。DataTable有一个键列ID, ID的值可以是1,2,3,4,5。

我想将comboBox的SelectedIndex设置为我想要的ID。这是我的尝试,它工作正常,但我不确定它是最好的:

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]);

你有更好的解决方案吗?

非常感谢!

将组合框的SelectedIndex设置为根据基础数据源中的键值找到的索引

我自己试过,但我不确定他们是否比我在原来的问题中发布的更好。如下:

  1. 使用BindingSourceFind()方法:

    //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. ComboBoxFindStringExact()方法使用一个小技巧:

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

SelectedIndexChanged触发时,如果您有与DisplayMember相关的事情要处理,则应小心使用#2。

我希望这有助于别人。如果它们比我在最初问题中使用的方法更好,请在下面留下你的评论。谢谢!