0

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 ?

Community
  • 1
  • 1
  • http://stackoverflow.com/questions/7562989/listbox-items-as-autocompletecustomsource-for-a-textbox – Facundo La Rocca Jan 06 '17 at 13:26
  • I think you woukld be much better using a combobox in DropDownStyle.Simple – NicoRiff Jan 06 '17 at 13:30
  • See [this](https://www.codeproject.com/tips/881637/type-ahead-suggestion-box-using-listbox) for a complete tutorial on how to do that. – CodingYoshi Jan 06 '17 at 13:34
  • @CodingYoshi thanks for your help. I solved my problem with base on that post. BTW there is a small typo, one bracket "{" is missing after this line: private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e) – Olexandr Baturin Jan 09 '17 at 15:35

4 Answers4

1

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.

1

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);
    }
}
Nick Allan
  • 387
  • 4
  • 10
0

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.

CDove
  • 1,940
  • 10
  • 19