我想在组合框中键入值,并过滤组合项,其中任何项都不包含我输入的文本。
因此,如果我有一个值为{“ one”,“ two”,“ three”}的组合框
我可以选择组合框,然后键入“ o”,这将为我提供“一个”和“两个”作为剩余选项。
我可以看到这个问题已经问过几次了,但是所有答案都非常冗长和尴尬-到目前为止,我最喜欢的示例是this.
有人知道实现这一目标的更明智的方法吗?
答案 0 :(得分:1)
您可以使用以下代码:
//Elements of the combobox
string[] ComboxBoxItems = { "one", "two", "three" };
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
//Gets the items that contains the search string and orders them by its position. Without the union items that don't contain the
//search string would be permanently removed from the combobox.
string[] UpdatedComboBoxItems = ComboxBoxItems.Where(x => x.Contains(comboBox1.Text)).OrderBy(x => x.IndexOf(comboBox1.Text)).ToArray();
//Removes every element from the combobox control. Combobox.Items.Clear causes the cursor position to reset.
foreach(string Element in ComboxBoxItems)
comboBox1.Items.Remove(Element);
//Re-adds all the element in order.
comboBox1.Items.AddRange(UpdatedComboBoxItems);
}
对于测试集合{“ one”,“ Two”,“ 3”},这些是与搜索字符串有关的输出:
答案 1 :(得分:1)
对于其他想要这样做的人,这是我最终使用(vb.net)的代码
Private Sub ComboKeyPressed() 'cbRPP = the checkbox. I true cbRPP.Sorted = true so I don't have to manually resort items
SyncLock "ComboKeyPressed"
cbRPP.DroppedDown = True
Cursor.Current = Cursors.Default
Dim s As String = cbRPP.Text.ToLower()
Dim toShow As IEnumerable(Of String) = cbRPPItems.Where(Function(x) x.ToLower().Contains(s.ToLower()))
If Not toShow.Any() Then
cbRPP.Items.Clear()
End If
Dim cbItems = New List(Of String)(cbRPP.Items.OfType(Of String).ToList())
Dim toRemove = cbItems.Except(toShow).ToList()
Dim toAdd = toShow.Except(cbItems)
For Each item In toAdd
cbRPP.Items.Add(item)
Next
For Each item In toRemove
cbRPP.Items.Remove(item)
Next
End SyncLock
End Sub