我有一个字符串“test1”,我的组合框包含test1、test2和test3。如何设置选中项为“test1”?也就是说,我如何匹配我的字符串到一个组合框项目?
我想的是下面这行,但这不行。
comboBox1.SelectedText = "test1";
我有一个字符串“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");
其他回答
假设test1、test2、test3属于comboBox1集合,下面的语句将工作。
comboBox1.SelectedIndex = 0;
你试过文本属性了吗?这对我很管用。
ComboBox1.Text = "test1";
SelectedText属性用于组合框的文本框部分中可编辑文本的选定部分。
我已经创建了一个函数,它将返回值的索引
public static int SelectByValue(ComboBox comboBox, string value)
{
int i = 0;
for (i = 0; i <= comboBox.Items.Count - 1; i++)
{
DataRowView cb;
cb = (DataRowView)comboBox.Items[i];
if (cb.Row.ItemArray[0].ToString() == value)// Change the 0 index if your want to Select by Text as 1 Index
{
return i;
}
}
return -1;
}
我知道这不是执勤人员要求的,但会不会是他们不知道呢?这里已经有几个答案,所以即使这很长,我认为它可能对社区有用。
使用枚举填充组合框可以方便地使用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();
}
_cmbTemplates.SelectedText = "test1"
或者
_cmbTemplates.SelectedItem= _cmbTemplates.Items.Equals("test1");