我有一个字符串“test1”,我的组合框包含test1、test2和test3。如何设置选中项为“test1”?也就是说,我如何匹配我的字符串到一个组合框项目?
我想的是下面这行,但这不行。
comboBox1.SelectedText = "test1";
我有一个字符串“test1”,我的组合框包含test1、test2和test3。如何设置选中项为“test1”?也就是说,我如何匹配我的字符串到一个组合框项目?
我想的是下面这行,但这不行。
comboBox1.SelectedText = "test1";
当前回答
这个方案是基于MSDN的,我做了一些修改。
It finds exact or PART of string and sets it. private int lastMatch = 0; private void textBoxSearch_TextChanged(object sender, EventArgs e) { // Set our intial index variable to -1. int x = 0; string match = textBoxSearch.Text; // If the search string is empty set to begining of textBox if (textBoxSearch.Text.Length != 0) { bool found = true; while (found) { if (comboBoxSelect.Items.Count == x) { comboBoxSelect.SelectedIndex = lastMatch; found = false; } else { comboBoxSelect.SelectedIndex = x; match = comboBoxSelect.SelectedValue.ToString(); if (match.Contains(textBoxSearch.Text)) { lastMatch = x; found = false; } x++; } } } else comboBoxSelect.SelectedIndex = 0; }
希望我能帮上忙!
其他回答
对我来说,这只管用:
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;
}
}
假设你的组合框没有绑定,你需要在你的表单上的“items”集合中找到对象的索引,然后设置“selectedindex”属性为适当的索引。
comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");
请记住,如果没有找到项目,IndexOf函数可能会抛出一个参数异常。
如果组合框中的项目是字符串,您可以尝试:
comboBox1.SelectedItem = "test1";
这对我有用.....
comboBox.DataSource.To<DataTable>().Select(" valueMember = '" + valueToBeSelected + "'")[0]["DislplayMember"];
请试试这个方法,它对我很有效:
Combobox1.items[Combobox1.selectedIndex] = "replaced text";