Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropdownlist Datasource and adding extra item from C#

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

like image 370
Sami Avatar asked Nov 28 '22 06:11

Sami


1 Answers

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>
like image 62
Yahoo Serious Avatar answered Dec 05 '22 19:12

Yahoo Serious