Search code examples
sqldatasourcepageload

SQLDataSource binds Data twice :(


this problem is driving me really mad.

In an Asp.Net-application, I have two DropDownLists, DropDownStore and DropDownCampaign.

<asp:DropDownList ID="storeDropDown" AppendDataBoundItems="true" 
     AutoPostBack="true" DataSourceID="storeSqlDataSource" 
     DataTextField="Name" DataValueField="StoreId" 
     runat="server" OnSelectedIndexChanged="storeDropDown_SelectedIndexChanged"> 
     <asp:ListItem Value="">Choose a store</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="campaignDropDown" DataSourceID="campaignSqlDataSource" 
     DataTextField="Name" DataValueField="CampaignLevelId" 
     AppendDataBoundItems="true" runat="server">
     <asp:ListItem Value="">Choose a campaign</asp:ListItem>
</asp:DropDownList>  

As you can see, they are both bound to SQLDataSources.

The SQLDataSource for the second DropDownList looks as follows:

<asp:SqlDataSource ID="campaignSqlDataSource"  runat="server" ConnectionString="<%$ ConnectionStrings:AFPMAdManagerConnectionString %>"
    SelectCommand="SELECT [CampaignLevelId], [Name] FROM [CampaignLevel] where [StoreId] = @StoreId">
    <SelectParameters>
        <asp:ControlParameter ControlID="storeDropDown" Name="StoreId" PropertyName="SelectedValue" Type="String" />
    </SelectParameters>        
</asp:SqlDataSource>    

so that the second DropDownList is bound, when the user chooses an entry of the first DropDownList.

This works well. But when I set the value of the first DropDownList programmatically, the second DropDownList is bound twice:

 protected void Page_Load(object sender, EventArgs e)
 {
    storeDropDown.SelectedValue = "someStore";       
 }

Why?


Solution

  • It's being told to bind twice. It binds on the original value of the first dropdown (since that's the controlID governing it), and then when you set it in Page_load event it binds it again.

    I would recommend binding it to a label with visible property set to False. Then on the first dropdown selectedindex changed, set the text property of the label.