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
?
If the DropDownList is declared in your aspx page and not in the codebehind, you can do it like this.
.aspx:
.aspx.cs:
When a dictionary is enumerated, it will yield
KeyValuePair<TKey,TValue>
objects... so you just need to specify "Value" and "Key" forDataTextField
andDataValueField
respectively, to select the Value/Key properties.Thanks to Joe's comment, I reread the question to get these the right way round. Normally I'd expect the "key" in the dictionary to be the text that's displayed, and the "value" to be the value fetched. Your sample code uses them the other way round though. Unless you really need them to be this way, you might want to consider writing your code as:
(And then changing the binding to use "Key" for
DataTextField
and "Value" forDataValueField
, of course.)In fact, I'd suggest that as it seems you really do want a list rather than a dictionary, you might want to reconsider using a dictionary in the first place. You could just use a
List<KeyValuePair<string, string>>
:Alternatively, use a list of plain
CultureInfo
values. LINQ makes this really easy:If you're not using LINQ, you can still use a normal foreach loop:
Like that you can set DataTextField and DataValueField of DropDownList using "Key" and "Value" texts :
Just use "Key" and "Value"