我有一个字符串“test1”,我的组合框包含test1、test2和test3。如何设置选中项为“test1”?也就是说,我如何匹配我的字符串到一个组合框项目?
我想的是下面这行,但这不行。
comboBox1.SelectedText = "test1";
我有一个字符串“test1”,我的组合框包含test1、test2和test3。如何设置选中项为“test1”?也就是说,我如何匹配我的字符串到一个组合框项目?
我想的是下面这行,但这不行。
comboBox1.SelectedText = "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。[0].ToString();
如果你通过数据集绑定数据源,那么你应该使用"SelectedValue"
cmbCategoryList.SelectedValue = (int)dsLookUp.Tables[0].Select("WHERE PRODUCTCATEGORYID = 1")[0]["ID"];
在组合框中没有这个属性。你有SelectedItem或SelectedIndex。如果你有用来填充组合框的对象,那么你可以使用SelectedItem。
如果不是,您可以获得项的集合(属性items),并迭代它,直到您获得想要的值,并将其与其他属性一起使用。
希望能有所帮助。
SelectedText用于在字符串编辑器中获取或设置组合框中所选项目的实际文本。如果你设置了:
comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
Use:
comboBox1.SelectedItem = "test1";
or:
comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");
combo.Items.FindByValue("1").Selected = true;