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

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

comboBox1.SelectedText = "test1"; 

当前回答

ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String");

在windows窗体中尝试此操作。

其他回答

这个方案是基于MSDN的,我做了一些修改。

It finds exact or PART of string and sets it. private int lastMatch = 0; private void textBoxSearch_TextChanged(object sender, EventArgs e) { // Set our intial index variable to -1. int x = 0; string match = textBoxSearch.Text; // If the search string is empty set to begining of textBox if (textBoxSearch.Text.Length != 0) { bool found = true; while (found) { if (comboBoxSelect.Items.Count == x) { comboBoxSelect.SelectedIndex = lastMatch; found = false; } else { comboBoxSelect.SelectedIndex = x; match = comboBoxSelect.SelectedValue.ToString(); if (match.Contains(textBoxSearch.Text)) { lastMatch = x; found = false; } x++; } } } else comboBoxSelect.SelectedIndex = 0; }

希望我能帮上忙!

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

comboBox1.SelectedItem = "test1";

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

comboBox1.SelectedIndex = 0; 

你试过文本属性了吗?这对我很管用。

ComboBox1.Text = "test1";

SelectedText属性用于组合框的文本框部分中可编辑文本的选定部分。

如果你通过数据集绑定数据源,那么你应该使用"SelectedValue"

cmbCategoryList.SelectedValue = (int)dsLookUp.Tables[0].Select("WHERE PRODUCTCATEGORYID = 1")[0]["ID"];