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

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

comboBox1.SelectedText = "test1"; 

当前回答

我已经填充了我的组合框与从数据库填充的数据表。然后我设置了DisplayMember和ValueMember。我使用这段代码来设置所选项目。

foreach (DataRowView Row in ComboBox1.Items)
{
    if (Row["ColumnName"].ToString() == "Value") ComboBox1.SelectedItem = Row;
}

其他回答

_cmbTemplates.SelectedText = "test1"

或者

_cmbTemplates.SelectedItem= _cmbTemplates.Items.Equals("test1");

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

        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;
        }

这应该可以达到目的:

Combox1.SelectedIndex = Combox1.FindStringExact("test1")

我使用KeyValuePair ComboBox数据绑定,我想通过值找到项目,所以这在我的情况下工作:

comboBox.SelectedItem = comboBox.Items.Cast<KeyValuePair<string,string>>().First(item=> item.Value == "value to match");

我已经填充了我的组合框与从数据库填充的数据表。然后我设置了DisplayMember和ValueMember。我使用这段代码来设置所选项目。

foreach (DataRowView Row in ComboBox1.Items)
{
    if (Row["ColumnName"].ToString() == "Value") ComboBox1.SelectedItem = Row;
}