我有一个字符串“test1”,我的组合框包含test1、test2和test3。如何设置选中项为“test1”?也就是说,我如何匹配我的字符串到一个组合框项目?
我想的是下面这行,但这不行。
comboBox1.SelectedText = "test1";
我有一个字符串“test1”,我的组合框包含test1、test2和test3。如何设置选中项为“test1”?也就是说,我如何匹配我的字符串到一个组合框项目?
我想的是下面这行,但这不行。
comboBox1.SelectedText = "test1";
当前回答
假设你的组合框没有绑定,你需要在你的表单上的“items”集合中找到对象的索引,然后设置“selectedindex”属性为适当的索引。
comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");
请记住,如果没有找到项目,IndexOf函数可能会抛出一个参数异常。
其他回答
我已经填充了我的组合框与从数据库填充的数据表。然后我设置了DisplayMember和ValueMember。我使用这段代码来设置所选项目。
foreach (DataRowView Row in ComboBox1.Items)
{
if (Row["ColumnName"].ToString() == "Value") ComboBox1.SelectedItem = Row;
}
combo.Items.FindByValue("1").Selected = true;
对我来说,这只管用:
foreach (ComboBoxItem cbi in someComboBox.Items)
{
if (cbi.Content as String == "sometextIntheComboBox")
{
someComboBox.SelectedItem = cbi;
break;
}
}
MOD:如果你有你自己的对象作为项目设置在组合框,然后替换ComboBoxItem与他们中的一个:
foreach (Debitor d in debitorCombo.Items)
{
if (d.Name == "Chuck Norris")
{
debitorCombo.SelectedItem = d;
break;
}
}
这应该可以达到目的:
Combox1.SelectedIndex = Combox1.FindStringExact("test1")
ListItem li = DropDownList.Items.FindByValue("13001");
DropDownList.SelectedIndex = ddlCostCenter.Items.IndexOf(li);
你的案子可以用
DropDownList.Items.FindByText("Text");