2

这个问题让我很生气。

在 Asp.Net 应用程序中,我有两个 DropDownList,DropDownStore 和 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>  

如您所见,它们都绑定到 SQLDataSource。

第二个 DropDownList 的 SQLDataSource 如下所示:

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

这样当用户选择第一个 DropDownList 的条目时,就绑定了第二个 DropDownList。

这很好用。但是当我以编程方式设置第一个 DropDownList 的值时,第二个 DropDownList 被绑定了两次

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

为什么?

4

3 回答 3

0

虽然我不知道双重绑定的确切原因,但最好的选择可能是OnDataBinding为第二个列表设置一个处理程序,在其中设置一个断点,然后检查两个位置的调用堆栈。这将告诉您为什么框架两次都绑定该列表。

根据您对性能的敏感程度,您可能只想在第二个列表中设置AppendDataBoundItemsfalse,这样重新绑定就无关紧要了。

于 2010-02-04T17:32:05.247 回答
0

它被告知绑定两次。它绑定在第一个下拉列表的原始值上(因为这是控制它的 controlID),然后当您在 Page_load 事件中设置它时,它会再次绑定它。

我建议将其绑定到可见属性设置为 False 的标签。然后在第一个下拉 selectedindex 更改时,设置标签的 text 属性。

于 2010-02-04T17:33:11.510 回答
0

尝试将您的选择包装在:

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
  {
    storeDropDown.SelectedValue = "someStore";       
  }
} 
于 2010-02-04T17:38:33.890 回答