Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've just come across this bizarre thing that I was expecting to work in a different (logical) way, but it doesn't. Is it a bug or a "feature"?

So there's a DropDownList that I'm populating in the codebehind with a List of ListItem. Each new ListItem gets 2 arguments that, according to the intellisense-provided documentation, correspond to its text and value:

List<ListItem> users = new List<ListItem>();
foreach (SubscriptionUser su in subscriptionDetails.UserList)
{
    users.Add(new ListItem(su.FirstName + " " + su.LastName, su.EmailAddress));
}
ddlPrimaryContact.DataSource = users;
ddlPrimaryContact.DataBind();

Now, can someone explain me why the databound DropDownList both the Text and Value set to exactly the same (the ListItem text) instead of using ListItem.Text as the Text and ListItem.Value as the Value?

ARGH!! http://www.freeimagehosting.net/uploads/fe65d0e7d5.jpg

Or am I doing something wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
505 views
Welcome To Ask or Share your Answers For Others

1 Answer

Hi when databinding (to anything) you need to set the DataTextField and DataValueField of your DropDownList. In your case you should use the following code

List<ListItem> users = new List<ListItem>();
foreach (SubscriptionUser su in subscriptionDetails.UserList)
{
    users.Add(new ListItem(su.FirstName + " " + su.LastName, su.EmailAddress));
}
ddlPrimaryContact.DataTextField = "Text";
ddlPrimaryContact.DataValueField = "Value";
ddlPrimaryContact.DataSource = users;
ddlPrimaryContact.DataBind();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...