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

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

comboBox1.SelectedText = "test1"; 

当前回答

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

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

其他回答

这应该可以达到目的:

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

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

comboBox1.SelectedIndex = 0; 

SelectedText用于在字符串编辑器中获取或设置组合框中所选项目的实际文本。如果你设置了:

comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;

Use:

comboBox1.SelectedItem = "test1";

or:

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

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

comboBox1.SelectedItem = "test1";
comboBox1.SelectedItem.Text = "test1";