我有一个字符串 "test1",我的组合框包含 test1
、test2
和 test3
。如何将选定的项目设置为 "test1"?也就是说,如何将我的字符串与组合框中的一个项目匹配?
我想到了下面这行代码,但它不起作用。
comboBox1.SelectedText = "test1";
在ComboBox没有父级之前,所有设置ComboBox项目的方法、技巧和代码行都不起作用。
combo.Items.FindByValue("1").Selected = true;
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();
}
comboBox1.Text = comboBox1.Items[0].ToString();
Combobox1.items[Combobox1.selectedIndex] = "replaced text";
它应该能工作。
Yourcomboboxname.setselecteditem("yourstring");
如果您想设置数据库字符串,请使用以下内容
Comboboxname.setselecteditem(ps.get string("databasestring"));
SelectedText
将“选定”的文本更改为 test1。如果没有进行“选择”(标记的文本),则文本将插入插入符号位置。 - AaA