数据绑定ASP.NET ListItem列表DropDownList问题 [英] Databind ASP.NET List of ListItem to DropDownList issue
问题描述
所以有一个DropDownList,我正在使用ListItem列表填充在codebehind中。每个新的ListItem得到两个参数,根据智能提供的文档,它们对应于其文本和值:
列表< ListItem> ; users = new List< ListItem>();
foreach(SubscriptionDetails.UserList中的SubscriptionUser su)
{
users.Add(new ListItem(su.FirstName ++ su.LastName,su.EmailAddress));
}
ddlPrimaryContact.DataSource = users;
ddlPrimaryContact.DataBind();
现在,有人可以解释我为什么数据绑定DropDownList的Text和Value都设置完全一样( ListItem文本),而不是使用ListItem.Text作为Text和ListItem.Value作为值?
ARGH! http://www.freeimagehosting.net/uploads/fe65d0e7d5.jpg
或者我做错了?
当数据绑定(任何东西)你需要设置你的DropDownList的DataTextField和DataValueField。在您的情况下,您应该使用以下代码
列表< ListItem> users = new List< ListItem>();
foreach(SubscriptionDetails.UserList中的SubscriptionUser su)
{
users.Add(new ListItem(su.FirstName ++ su.LastName,su.EmailAddress));
}
ddlPrimaryContact.DataTextField =Text;
ddlPrimaryContact.DataValueField =Value;
ddlPrimaryContact.DataSource = users;
ddlPrimaryContact.DataBind();
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?
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();
这篇关于数据绑定ASP.NET ListItem列表DropDownList问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!