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

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

问题描述

我刚刚碰到,我期待在不同的(逻辑)的方式来解决这个离奇的事情,但事实并非如此。它是一个bug,还是一个功能?

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

因此​​,有我正在填充在codebehind与列表项的列表一个DropDownList。每一个新的列表项获得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的文本和值分别设置两个完全相同的(在列表项文本)而不是使用ListItem.Text作为文本和ListItem.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?

还是我做错了什么?

推荐答案

数据绑定(任何事情),你需要设置你的DropDownList的DataTextField和DataValueField时喜。在你的情况,你应该使用下面的code

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列表为DropDownList问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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