从通用列表中将ListItem添加到DropDownList [英] Adding ListItems to a DropDownList from a generic list

查看:111
本文介绍了从通用列表中将ListItem添加到DropDownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这个aspx代码:(sample)

I have a this aspx-code: (sample)

<asp:DropDownList runat="server" ID="ddList1"></asp:DropDownList>   

使用此codebehind:

With this codebehind:

List<System.Web.UI.WebControls.ListItem> colors = new List<System.Web.UI.WebControls.ListItem>();
colors.Add(new ListItem("Select Value", "0"));
colors.Add(new ListItem("Red", "1"));
colors.Add(new ListItem("Green", "2"));
colors.Add(new ListItem("Blue", "3"));
ddList1.DataSource = colors;
ddList1.DataBind();

输出如下所示:

<select name="ddList1" id="ddList1">
    <option value="Select Value">Select Value</option>
    <option value="Red">Red</option>
    <option value="Green">Green</option>
    <option value="Blue">Blue</option>
</select>   

我的问题是:为什么我的值(数字)消失,文本用作值AND文本?我知道如果我使用 ddList1.Items.Add(New ListItem(text,value))方法,但我需要使用通用列表作为数据源的其他原因。

My question is: Why did my values (numbers) disappear and the text used as the value AND the text? I know that it works if I use the ddList1.Items.Add(New ListItem("text", "value")) method, but I need to use a generic list as the datasource for other reasons.

推荐答案

因为DataBind方法只有在DataValueField属性设置时才绑定值。如果在调用DataBind之前将DataValueField属性设置为Value,您的值将显示在标记上。

Because DataBind method binds values only if DataValueField property is set. If you set DataValueField property to "Value" before calling DataBind, your values will appear on the markup.

更新:您还需要将DataTextField属性设置为Text 。这是因为手动的数据绑定和添加项不能以同样的方式工作。数据绑定不知道类型ListItem的存在,并通过评估数据源中的项来生成标记。

UPDATE: You will also need to set DataTextField property to "Text". It is because data binding and adding items manually do not work in the same way. Databinding does not know the existence of type ListItem and generates markup by evaluating the items in the data source.

这篇关于从通用列表中将ListItem添加到DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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