Adding an additional item to a dropdownlist datasource from C#

.net-4.0 c# drop-down-menu entity-framework


I possessDropDownList that is connected to aDataSource inside the ASPX page. When the page loads, I still need to add one more thing.

I'm Code:

<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" 
     DefaultContainerName="Entities" EnableFlattening="False" 

And I'm attempting to add this additional item:

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

The code runs through it when I debug it. But When the page is displayed dropdown doesn't contain"None" .

5/15/2014 9:36:04 PM

Accepted Answer

You're most likely inserting the item before the because of this.DataBind() If you wish to include anything with


After then, you must complete the task since the dropdown menu is bound.

You can see that DataBind is being executed in PreRenderComplete by looking at Therefore, you must include the element in an event that follows PreRenderComplete. You might also complete it on theddlVisualTemplate.DataBound event.

6/30/2011 10:24:14 PM

Popular Answer

Although probably too late for the original poster, this information could be helpful to other users:

You may include "None," "Choose value," and other values in the designer (or the code) to avoidDataBind keeping from altering it, by settingAppendDataBoundItems="true" This will result inDataBind rather than clarify, add.

See Scott Guthrie's post In ASP.NET 2.0, the ListControl.AppendDataBoundItems Property for an illustration.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow