开发者

Autocomplete textbox collection

In windows forms a textbox can be made into an autocomplete textbox by giving it a开发者_StackOverflow中文版 simple list of strings or by giving it a custom source that can only be a AutoCompleteCollection which is a strong typed list of strings. I would like to be able to add a key to each string..so that whenever any suggestion is selected I can grab that key.

I might just be drawing a blank..but does anyone have a suggestion ? Thanks in advance


The class AutoCompleteStringCollection is not sealed so you could certainly derive from it and create an overload of Add that takes two parameters: a key and a value.

Then you can track that in a dictionary. You'll have to store the string twice (once in the base class's collection and once in your dictionary) but you can then add a lookup method like so:

class KeyedAutoCompleteStringCollection : AutoCompleteStringCollection {

    private readonly Dictionary<string,string> keyedValues =
        new Dictionary<string,string>(StringComparer.OrdinalIgnoreCase);

    public void Add(string value, string key) {
        base.Add(value);
        keyedValues.Add(value, key); // intentionally backwards
    }

    public string Lookup(string value) {
        string key;
        if (keyedValues.TryGetValue(value, out key)) {
            return key;
        }
        else {
            return null;
        }
    }

}


If I understand you correctly, you want the value in the text box (which can be auto suggested) to have an associated value. You could do that by creating a Dictionary<string, string> with the TextBox text as the key and what you are calling the 'key' as the value. Whenever you want to locate the 'key' for a particular TextBox value, you can check the dictionary for it.

Of course, a TextBox may not be the best way to represent your data if there must be a key. If there must be a key, the ComboBox (with DropDownStyle set to ComboBoxStyle.DropDownList) might be a better option.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜