114

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?

4 Answers 4

213

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();
Sign up to request clarification or add additional context in comments.

5 Comments

I'd recommend setting TextField to "key" and ValueField to Value. I think that's more intuitive.
@MGOwen It may seem intuitive to set DataValueField to Value, because of the common "Value", but it is actually illogical in regular use of the datastructure/control. For details on this, see my comment on Jon Skeet's answer.
I don't see a list.Add that takes 2 args.. only one that takes one arg. is this winforms??
@hrh then you are probably not using a Dictionary<TKey, TValue>, but maybe a List<T>.
@Canavar is it possible to set the DataText field as "key-Value" ....? How can i do it.
11

When a dictionary is enumerated, it will yield KeyValuePair<TKey,TValue> objects... so you just need to specify "Value" and "Key" for DataTextField and DataValueField 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:

list.Add(cul.DisplayName, cod);

(And then changing the binding to use "Key" for DataTextField and "Value" for DataValueField, 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>>:

string[] languageCodsList = service.LanguagesAvailable();
var list = new List<KeyValuePair<string, string>>();

foreach (string cod in languageCodsList)
{
    CultureInfo cul = new CultureInfo(cod);
    list.Add(new KeyValuePair<string, string>(cul.DisplayName, cod));
}

Alternatively, use a list of plain CultureInfo values. LINQ makes this really easy:

var cultures = service.LanguagesAvailable()
                      .Select(language => new CultureInfo(language));
languageList.DataTextField = "DisplayName";
languageList.DataValueField = "Name";
languageList.DataSource = cultures;
languageList.DataBind();

If you're not using LINQ, you can still use a normal foreach loop:

List<CultureInfo> cultures = new List<CultureInfo>();
foreach (string cod in service.LanguagesAvailable())
{
    cultures.Add(new CultureInfo(cod));
}
languageList.DataTextField = "DisplayName";
languageList.DataValueField = "Name";
languageList.DataSource = cultures;
languageList.DataBind();

3 Comments

Actually, this is incorrect - see my comment on the accepted answer.
Ah, I'd misread the question. It seems confusing to me to put them in a dictionary the "wrong" way round. Will edit my answer.
@JonSkeet The reason for the "backwards" association is that the data being stored in the dictionary as a key/value pair normally uses the key (lookup value) as a data association (eg. for database referencing), and in a dropdown list, this corresponds to the DataValueField, i.e. the return value of a POST, which tells you more about the selected item than the DataTextField, i.e. the display value. (DropDownLists just have a poor naming convention)
7

If the DropDownList is declared in your aspx page and not in the codebehind, you can do it like this.

.aspx:

<asp:DropDownList ID="ddlStatus" runat="server" DataSource="<%# Statuses %>"
     DataValueField="Key" DataTextField="Value"></asp:DropDownList>

.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
    ddlStatus.DataBind();
    // or use Page.DataBind() to bind everything
}

public Dictionary<int, string> Statuses
{
    get 
    {
        // do database/webservice lookup here to populate Dictionary
    }
};

1 Comment

Upvoted. It is noteworthy that it is REQUIRED that this be a server-side object to be evaluated. You can't pass it inline using <%# syntax %> . Whether that be a <script runat="server">, or as seen in Matt's example above, upto you. It does indeed work.
5

Just use "Key" and "Value"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.