views:

30

answers:

2

Is there a way to make a windows forms combo-box read-only? To be specific: the user should be able to type, but only those values within the box should be allowed (using auto-complete or a select from the list).

Or is the only way to use the validating event?

Regards

Mario

+3  A: 

You can set the DropDownStyle to DropDownList, but that does not really allow typing (but it does allow selecting with the keyboard).

If you do want the user to be able to type/see incomplete words, you will have to use an event. The Validating event would be the best choice.

Henk Holterman
Thanks! I just wanted I could do without coding it myself... Guess another library component for my set...
Mario The Spoon
+3  A: 

If you set AutoCompleteMode = SuggestAppend and AutoCompleteSource = ListItems when a user type something, automatically the combobox show entries that starts with the typed characters.

Then by handling SelectedIndexChanged or SelectedValueChanged events, you will able to intercept when a user type exactly a value present in the values list.

If you also absolutely don't want user to type anything that's not in the list, well yes, you have to handle for example KeyDown event like:

private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
    char ch = (char)e.KeyValue;
    if (!char.IsControl(ch))
    {
        string newTxt = this.comboBox1.Text + ch;
        bool found = false;
        foreach (var item in this.comboBox1.Items)
        {
            string itemString = item.ToString();
            if (itemString.StartsWith(newTxt, StringComparison.CurrentCultureIgnoreCase))
            {
                found = true;
                break;
            }
        }
        if (!found)
            e.SuppressKeyPress = true;
    }
}
digEmAll
Thanks, I was afraid I had to do that!
Mario The Spoon