Adding an additional item to a dropdownlist datasource from C#

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

Question

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.

My 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" 
     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".

1
3
5/15/2014 9:36:04 PM

Accepted Answer

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.

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.

11
6/30/2011 10:24:14 PM

Popular Answer

Probably too late for the original poster, but maybe useful for other users:

You can add the value "None", "Choose value", etc. in the designer (or in the code) and prevent DataBind from overwriting it, by setting AppendDataBoundItems="true". This will make DataBind append rather than clear.

For an example see Scott Guthrie's post ListControl.AppendDataBoundItems Property in ASP.NET 2.0.



Related Questions





Related

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