我有一个字符串 "test1",我的组合框包含 test1
、test2
和 test3
。如何将选定的项目设置为 "test1"?也就是说,如何将我的字符串与组合框中的一个项目匹配?
我想到了下面这行代码,但它不起作用。
comboBox1.SelectedText = "test1";
这应该能解决问题:
Combox1.SelectedIndex = Combox1.FindStringExact("test1")
假设你的组合框不是数据绑定的,你需要在表单的“items”集合中找到该对象的索引,然后将“selectedindex”属性设置为相应的索引。
comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");
请记住,IndexOf函数如果未找到该项可能会抛出ArgumentException异常。
null
传递给 IndexOf
方法时,它才会抛出异常。如果未找到该项,则仅返回 -1(这恰好是 SelectedIndex
的有效值)。 - Ben Voigt如果ComboBox中的项目是字符串,您可以尝试:
comboBox1.SelectedItem = "test1";
ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String");
尝试在Windows窗体中执行此操作。
对我而言,只有这个方法可行:
foreach (ComboBoxItem cbi in someComboBox.Items)
{
if (cbi.Content as String == "sometextIntheComboBox")
{
someComboBox.SelectedItem = cbi;
break;
}
}
如果您在ComboBox中设置了自己的对象作为项目,那么请将ComboBoxItem替换为其中之一,例如:
foreach (Debitor d in debitorCombo.Items)
{
if (d.Name == "Chuck Norris")
{
debitorCombo.SelectedItem = d;
break;
}
}
SelectedText用于获取或设置组合框中所选项目的字符串编辑器中的实际文本,如此处所述。如果设置以下内容,则无法进行编辑:
comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
使用:
comboBox1.SelectedItem = "test1";
或者:
comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");
Items.Count == 0
),Items
也始终是一个非空集合。 - Ben Voigt我使用了一个扩展方法:
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);
comboBox1.SelectedItem.Text = "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;
}
我希望我能帮到您!
SelectedText
将“选定”的文本更改为 test1。如果没有进行“选择”(标记的文本),则文本将插入插入符号位置。 - AaA