数据绑定ASP.NET ListItem列表DropDownList问题 [英] Databind ASP.NET List of ListItem to DropDownList issue

查看:187
本文介绍了数据绑定ASP.NET ListItem列表DropDownList问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚遇到这样一个奇怪的事情,我期待着以不同的(逻辑的)方式工作,但是它并没有。是否是一个错误或功能?



所以有一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆