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

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

comboBox1.SelectedText = "test1"; 

当前回答

请试试这个方法,它对我很有效:

Combobox1.items[Combobox1.selectedIndex] = "replaced text";

其他回答

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

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

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

这应该可以达到目的:

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

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

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

在windows窗体中尝试此操作。

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

comboBox1.SelectedItem = "test1";