我有一个字符串“test1”,我的组合框包含test1、test2和test3。如何设置选中项为“test1”?也就是说,我如何匹配我的字符串到一个组合框项目?
我想的是下面这行,但这不行。
comboBox1.SelectedText = "test1";
我有一个字符串“test1”,我的组合框包含test1、test2和test3。如何设置选中项为“test1”?也就是说,我如何匹配我的字符串到一个组合框项目?
我想的是下面这行,但这不行。
comboBox1.SelectedText = "test1";
当前回答
combo.Items.FindByValue("1").Selected = true;
其他回答
我使用KeyValuePair ComboBox数据绑定,我想通过值找到项目,所以这在我的情况下工作:
comboBox.SelectedItem = comboBox.Items.Cast<KeyValuePair<string,string>>().First(item=> item.Value == "value to match");
在组合框中没有这个属性。你有SelectedItem或SelectedIndex。如果你有用来填充组合框的对象,那么你可以使用SelectedItem。
如果不是,您可以获得项的集合(属性items),并迭代它,直到您获得想要的值,并将其与其他属性一起使用。
希望能有所帮助。
这个方案是基于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; }
希望我能帮上忙!
在组合框中枚举ListItems 获得相等的列表索引集组合框 将listindex设置为找到的值。
但如果我作为代码评审员看到这样的代码,我会建议重新考虑所有的方法算法。
SelectedText用于在字符串编辑器中获取或设置组合框中所选项目的实际文本。如果你设置了:
comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
Use:
comboBox1.SelectedItem = "test1";
or:
comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");