Make a Searchable ComboBox with .NETwith C# or VB.NET | | Have you wanted to make a searchable ComboBox in .NET? Well, it's pretty easy. There are many ways to implement this, but in a nutshell, all you need to do is trap the KeyPress event, use the KeyPress' Keychar and then call the ComboBox's FindString method. If you don't find the search text, you'll return a -1 as an index, if you do find the text, then the index will be the index the item exists in the list. So, if we find the text, we don't want to allow the keypress, otherwise we'd have 2 first letters in the combobox. However if you don't want to find it, you wan't to let them type in a value. Here's all there is to it:
VB.NET
Private Sub CombBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress
Dim findString As String = String.Empty
If (Not e.KeyChar.IsLetterOrDigit(e.KeyChar, 0)) Then Exit Sub
findString = e.KeyChar
With ComboBox1
.SelectedIndex = ComboBox1.FindString(findString)
End With
If ComboBox1.SelectedIndex > -1 Then e.Handled = True
End Sub |
C#
private void comboBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
string findString = string.Empty;
comboBox1.SelectedIndex = comboBox1.FindString(e.KeyChar.ToString());
if(comboBox1.SelectedIndex > -1){e.Handled = true;}
} | |