Sami Sami - 1 year ago 127
ASP.NET (C#) Question

Dropdownlist Datasource and adding extra item from C#

I have a

that is associated with a
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"
DefaultContainerName="Entities" EnableFlattening="False"

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

Answer Source

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


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

If you look at 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download