views:

7724

answers:

1

I have a Combobox control on my form (WinForms, .NET 3.5), and its DropDownStyle property is set to Simple. Let's say it is populated with the letters of the alphabet, as string objects ("a", "b", "c", and so on).
As I type a letter in the combobox' input field, the correct item will be displayed just underneath.

This is the behaviour I want. But I would also like to have the first matching item selected.

Is there a property of the Combobox control that would achieve that? Or do I need to handle that programatically?

+1  A: 

Depending on your needs, you might consider using a TextBox control and setting up the AutoComplete properties (e.g. AutoCompleteMode and AutoCompleteCustomSource)

The difficulty you're going to face is that once you select an item (programatically), the text in the combo box will change. So doing something like this:

private void comboBox1_TextChanged(object sender, EventArgs e)
{
    for(int i=0; i<comboBox1.Items.Count; i++)
    {
        if (comboBox1.Items[i].ToString().StartsWith(comboBox1.Text))
        {
            comboBox1.SelectedIndex = i;
            return;
        }
    }
}

might accomplish what you want (in terms of the selection), but it will also immediately change the user's text.

Daniel LeCheminant
helped me :) thank you.I had a problem with setting SelectedItem in combobox.
nihi_l_ist
I was hoping for an "easier" solution, and waiting for other people to answer, but it seems I will have to do it the "hard" way :/Thanks for your proposed solution!
Fueled
Well I do the TextBox with autocomplete; that's the "easy" way for me... but I don't think it quite suits your needs.
Daniel LeCheminant