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

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

comboBox1.SelectedText = "test1"; 

当前回答

在组合框中没有这个属性。你有SelectedItem或SelectedIndex。如果你有用来填充组合框的对象,那么你可以使用SelectedItem。

如果不是,您可以获得项的集合(属性items),并迭代它,直到您获得想要的值,并将其与其他属性一起使用。

希望能有所帮助。

其他回答

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

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

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

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

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

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

        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;
        }
_cmbTemplates.SelectedText = "test1"

或者

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

所有设置组合框项的方法、技巧和代码行都将在组合框具有父级之前不起作用。