Wednesday, April 29, 2009

Create a Checked Listbox with Key/Values Pairs

Sometimes, there is a need to display one set of strings in a checked listbox and use a different one in your code. For example, a user selects 'Washington', and you want the code to use 'WA'.
If that's the case, a Dictionary object will suit your needs. First, let's start with building a Dictionary:


public Dictionary<string, string> dicStates = new Dictionary<string, string>
        {
            { "Washington", "WA"},
            {"New York", "NY"},
            {"Texas", "TX"}
        };


Strings to be displayed in the checked listbox become dictionary keys, and strings to be used in your code become dictionary values.

Then, in your form constructor you populate the CheckedListBox:
foreach (var item in dicStates )
{
    clb1.Items.Add(item.Key);
}



To capture user-selected values, use the following code:


foreach (var key in clb1.CheckedItems)
{
    string val = string.Empty;
    dicStates .TryGetValue(key.ToString(), out val);
}


The string val will hold the Dictionary value - WA, NY or TX depending on the user selection.

2 comments:

  1. public Dictionary dicStates = new Dictionary
    {
    { "Washington", "WA"},
    {"New York", "NY"},
    {"Texas", "TX"}
    };

    Not working

    ReplyDelete
  2. Of course, since Dictionary is a generic class, it should be
    public Dictionary <string, string> dicStates = new Dictionary <string, string>...

    ReplyDelete