下拉列表数据源并添加额外的项目从C# [英] Dropdownlist Datasource and adding extra item from C#

查看:154
本文介绍了下拉列表数据源并添加额外的项目从C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 DropDownList ,它与aspx页面中的 DataSource 相关联。当页面加载时,我需要添加一个项目。

I have a DropDownList that is associated with a DataSource in the aspx page. I need to add one more item when the page is loaded.

我的代码:

<asp:LabelDropDownList ID="ddlVisualTemplate" runat="server" LabelText="Visual Template:"      DataSourceID="VisualTemplateDataSource" DataTextField="Name" DataValueField="Id" AutoPostBack="true" OnSelectedIndexChanged="ddlVisualTemplate_SelectedIndexChanged"/>                         

<asp:EntityDataSource ID="VisualTemplateDataSource" runat="server" 
     ConnectionString="name=Entities" 
     DefaultContainerName="Entities" EnableFlattening="False" 
     EntitySetName="tbEmailVisualTemplates">

我正尝试一个额外的项目:

And I am trying to an extra item to it:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ddlVisualTemplate.Items.Add(new ListItem("None", string.Empty));
        }
    }

如果我调试代码,它会通过它。但是当页面显示时,下拉菜单中不包含

If I debug the code, it goes through it. But When the page is displayed dropdown doesn't contain "None".

推荐答案

很可能是因为您在 DataBind()之前添加项目。如果你想添加一个项目

It's most probably because you're adding the item before the DataBind(). If you want to add an item with

ddlVisualTemplate.Items.Add()

那么你必须在之后下载下来。

then you have to do it after the dropdown is being bound.

如果您查看 http://msdn.microsoft.com/en- us / library / ms178472.aspx ,然后在PreRenderComplete中完成DataBind。因此,您必须在PreRenderComplete之后发生的某些事件中添加元素。
或者您可以在 ddlVisualTemplate.DataBound 事件上执行。

If you look at http://msdn.microsoft.com/en-us/library/ms178472.aspx then DataBind is being done in PreRenderComplete. So you have to add the element in some event that occurs after PreRenderComplete. Or you could do it on the ddlVisualTemplate.DataBound event.

这篇关于下拉列表数据源并添加额外的项目从C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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