我有一个字符串“test1”,我的组合框包含test1、test2和test3。如何设置选中项为“test1”?也就是说,我如何匹配我的字符串到一个组合框项目?
我想的是下面这行,但这不行。
comboBox1.SelectedText = "test1";
我有一个字符串“test1”,我的组合框包含test1、test2和test3。如何设置选中项为“test1”?也就是说,我如何匹配我的字符串到一个组合框项目?
我想的是下面这行,但这不行。
comboBox1.SelectedText = "test1";
当前回答
如果你通过数据集绑定数据源,那么你应该使用"SelectedValue"
cmbCategoryList.SelectedValue = (int)dsLookUp.Tables[0].Select("WHERE PRODUCTCATEGORYID = 1")[0]["ID"];
其他回答
我使用了一个扩展方法:
public static void SelectItemByValue(this ComboBox cbo, string value)
{
for(int i=0; i < cbo.Items.Count; i++)
{
var prop = cbo.Items[i].GetType().GetProperty(cbo.ValueMember);
if (prop!=null && prop.GetValue(cbo.Items[i], null).ToString() == value)
{
cbo.SelectedIndex = i;
break;
}
}
}
然后使用该方法:
ddl.SelectItemByValue(value);
在组合框中没有这个属性。你有SelectedItem或SelectedIndex。如果你有用来填充组合框的对象,那么你可以使用SelectedItem。
如果不是,您可以获得项的集合(属性items),并迭代它,直到您获得想要的值,并将其与其他属性一起使用。
希望能有所帮助。
应该可以
Yourcomboboxname.setselecteditem("yourstring");
如果你想设置数据库字符串,使用这个
Comboboxname.setselecteditem(ps.get string("databasestring"));
我使用KeyValuePair ComboBox数据绑定,我想通过值找到项目,所以这在我的情况下工作:
comboBox.SelectedItem = comboBox.Items.Cast<KeyValuePair<string,string>>().First(item=> item.Value == "value to match");
comboBox1.SelectedItem.Text = "test1";