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

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

comboBox1.SelectedText = "test1"; 

当前回答

我使用了一个扩展方法:

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

其他回答

如果组合框中的项目是字符串,您可以尝试:

comboBox1.SelectedItem = "test1";
combo.Items.FindByValue("1").Selected = true;
ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String");

在windows窗体中尝试此操作。

  ListItem li = DropDownList.Items.FindByValue("13001");
  DropDownList.SelectedIndex = ddlCostCenter.Items.IndexOf(li);

你的案子可以用

DropDownList.Items.FindByText("Text");

在组合框中枚举ListItems 获得相等的列表索引集组合框 将listindex设置为找到的值。

但如果我作为代码评审员看到这样的代码,我会建议重新考虑所有的方法算法。