SQLDataSource binds Data twice :(

久未见 提交于 2021-01-27 18:00:36

问题


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?


回答1:


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.




回答2:


While I don't know the exact reason for the double binding, your best bet might be to set an OnDataBinding handler for the second list, set a breakpoint in it, and examine the call stack in both places. That'll tell you why the framework is binding that list, both times.

Depending on how sensitive to performance you are, you might want to just set AppendDataBoundItems to false on the second list so that it doesn't matter that it's re-bound.




回答3:


Try wrapping your selection in:

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


来源:https://stackoverflow.com/questions/2201777/sqldatasource-binds-data-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!