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"
.
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.
Below example from Scott Guthrie's post ListControl.AppendDataBoundItems Property in ASP.NET 2.0.
<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server" DataSourceID="SqlDataSource1" DataTextField="state" DataValueField="state">
<asp:ListItem Text="(Select a State)" Value="" />
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:pubsConnectionString %>"
SelectCommand="SELECT DISTINCT [state] FROM [authors]">
</asp:SqlDataSource>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With