我有一个字符串“test1”,我的组合框包含test1、test2和test3。如何设置选中项为“test1”?也就是说,我如何匹配我的字符串到一个组合框项目?
我想的是下面这行,但这不行。
comboBox1.SelectedText = "test1";
我有一个字符串“test1”,我的组合框包含test1、test2和test3。如何设置选中项为“test1”?也就是说,我如何匹配我的字符串到一个组合框项目?
我想的是下面这行,但这不行。
comboBox1.SelectedText = "test1";
当前回答
你试过文本属性了吗?这对我很管用。
ComboBox1.Text = "test1";
SelectedText属性用于组合框的文本框部分中可编辑文本的选定部分。
其他回答
我已经填充了我的组合框与从数据库填充的数据表。然后我设置了DisplayMember和ValueMember。我使用这段代码来设置所选项目。
foreach (DataRowView Row in ComboBox1.Items)
{
if (Row["ColumnName"].ToString() == "Value") ComboBox1.SelectedItem = Row;
}
comboBox1.SelectedItem.Text = "test1";
如果组合框中的项目是字符串,您可以尝试:
comboBox1.SelectedItem = "test1";
我知道这不是执勤人员要求的,但会不会是他们不知道呢?这里已经有几个答案,所以即使这很长,我认为它可能对社区有用。
使用枚举填充组合框可以方便地使用SelectedItem方法以编程方式在组合框中选择项目,以及从组合框中加载和读取。
public enum Tests
{
Test1,
Test2,
Test3,
None
}
// Fill up combobox with all the items in the Tests enum
foreach (var test in Enum.GetNames(typeof(Tests)))
{
cmbTests.Items.Add(test);
}
// Select combobox item programmatically
cmbTests.SelectedItem = Tests.None.ToString();
如果你双击组合框,你可以处理选定的索引改变事件:
private void cmbTests_SelectedIndexChanged(object sender, EventArgs e)
{
if (!Enum.TryParse(cmbTests.Text, out Tests theTest))
{
MessageBox.Show($"Unable to convert {cmbTests.Text} to a valid member of the Tests enum");
return;
}
switch (theTest)
{
case Tests.Test1:
MessageBox.Show("Running Test 1");
break;
case Tests.Test2:
MessageBox.Show("Running Test 2");
break;
case Tests.Test3:
MessageBox.Show("Running Test 3");
break;
case Tests.None:
// Do nothing
break;
default:
MessageBox.Show($"No support for test {theTest}. Please add");
return;
}
}
然后可以从按钮单击处理程序事件运行测试:
private void btnRunTest1_Click(object sender, EventArgs e)
{
cmbTests.SelectedItem = Tests.Test1.ToString();
}
ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String");
在windows窗体中尝试此操作。