我有一个字符串“test1”,我的组合框包含test1、test2和test3。如何设置选中项为“test1”?也就是说,我如何匹配我的字符串到一个组合框项目?

我想的是下面这行,但这不行。

comboBox1.SelectedText = "test1"; 

当前回答

这对我有用.....

comboBox.DataSource.To<DataTable>().Select(" valueMember = '" + valueToBeSelected + "'")[0]["DislplayMember"];

其他回答

我已经创建了一个函数,它将返回值的索引

        public static int SelectByValue(ComboBox comboBox, string value)
        {
            int i = 0;
            for (i = 0; i <= comboBox.Items.Count - 1; i++)
            {
                DataRowView cb;
                cb = (DataRowView)comboBox.Items[i];
                if (cb.Row.ItemArray[0].ToString() == value)// Change the 0 index if your want to Select by Text as 1 Index
                {
                    return i;
                }
            }
            return -1;
        }

假设你的组合框没有绑定,你需要在你的表单上的“items”集合中找到对象的索引,然后设置“selectedindex”属性为适当的索引。

comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");

请记住,如果没有找到项目,IndexOf函数可能会抛出一个参数异常。

ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String");

在windows窗体中尝试此操作。

假设test1、test2、test3属于comboBox1集合,下面的语句将工作。

comboBox1.SelectedIndex = 0; 

我使用了一个扩展方法:

public static void SelectItemByValue(this ComboBox cbo, string value)
{
    for(int i=0; i < cbo.Items.Count; i++)
    {
        var prop = cbo.Items[i].GetType().GetProperty(cbo.ValueMember);
        if (prop!=null && prop.GetValue(cbo.Items[i], null).ToString() == value)
        {
             cbo.SelectedIndex = i;
             break;
        }
    } 
}

然后使用该方法:

ddl.SelectItemByValue(value);