C# DropDownList with a Dictionary as DataSource

VansFannel picture VansFannel · Apr 30, 2009 · Viewed 118.3k times · Source

I want to set DataTextField and DataValueField of a Dropdownlist (languageList) using a Dictionary (list) of languageCod (en-gb) as key and language name (english) as the text to display.

Relevant Code:

string[] languageCodsList= service.LanguagesAvailable();
Dictionary<string, string> list = 
                   new Dictionary<string, string>(languageCodsList.Length);

foreach (string cod in languageCodsList)
{
    CultureInfo cul = new CultureInfo(cod);
    list.Add(cod, cul.DisplayName);
}
languageList.DataSource = list;
languageList.DataBind();

How can I set DataTextField and DataValueField?

Answer

Canavar picture Canavar · Apr 30, 2009

Like that you can set DataTextField and DataValueField of DropDownList using "Key" and "Value" texts :

    Dictionary<string, string> list = new Dictionary<string, string>();
    list.Add("item 1", "Item 1");
    list.Add("item 2", "Item 2");
    list.Add("item 3", "Item 3");
    list.Add("item 4", "Item 4");

    ddl.DataSource = list;
    ddl.DataTextField = "Value";
    ddl.DataValueField = "Key";
    ddl.DataBind();