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

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

问题描述

我刚刚遇到了这个奇怪的事情,我希望以不同的(合乎逻辑的)方式工作,但事实并非如此.这是错误还是功能"?

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"?

所以我在代码隐藏中填充了一个 DropDownList,其中包含一个 ListItem 列表.每个新的 ListItem 都有 2 个参数,根据智能感知提供的文档,它们对应于它的文本和值:

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();

现在,谁能解释一下为什么数据绑定 DropDownList 的 Text 和 Value 设置为完全相同(ListItem 文本),而不是使用 ListItem.Text 作为 Text 和 ListItem.Value 作为 Value?

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?

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

还是我做错了什么?

推荐答案

当数据绑定(到任何东西)时,您需要设置 DropDownList 的 DataTextField 和 DataValueField.在您的情况下,您应该使用以下代码

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();

这篇关于将 ListItem 的 ASP.NET 列表数据绑定到 DropDownList 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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