Selecting an item in windows form listbox by typing?

1.4k Views Asked by At

I have a listbox with country names. I´m using Windows Forms in VS2015 (C#).
While selecting a name in listBox by typing, it only allows one letter. So if I type "A" it will jump to the first item starting with "A" but if I press "As", listbox viewing the items starting with "s". I found this answer for combobox and textbox:
Selecting an item in comboBox by typing
but look's like listbox doesn't support AutoCompleteMode. Is there any solution ?

4

There are 4 best solutions below

0
On

Please, consider implementing your own searching method. ListBox doesn't support required functionallity by design. Anyway, you can prepare a method on TextChanged event for TextBox which at the time searches for results in collection.

2
On
1
On

You should use a ComboBox with DropDownStyle.Simple. The ListBox was never intended to have this functionality, and forcing it to do so is usually a waste of time better spent.

You may also want to consider a third party control. Telerik, for example, has the DropDownList which extends a ComboBox and makes it do exactly what you want to do, with options on how it does it.

0
On

Here's some sample code. Drop a TextBox above your ListBox. Wire up the TextChanged event appropriately, and this should mimic the autocomplete behaviour of a ComboBox (for example)...

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        listBox1.Items.AddRange(new[] { "Tom", "Dick", "Harry", "Henry" });
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        var textBox = (TextBox)sender;
        listBox1.SelectedIndex = textBox.TextLength == 0 ?
            -1 : listBox1.FindString(textBox.Text);
    }
}