2010-02-04 66 views
2

這個問題讓我真的瘋了。SqlDataSource的數據綁定兩次:(

在一個Asp.Net的應用程序,我有兩個DropDownLists,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> 

正如你所看到的,它們都必然要SQLDataSources

看起來在SqlDataSource第二的DropDownList如下:

<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";  
} 

爲什麼?

回答

0

它被告知綁定兩次。它綁定在第一個下拉菜單的原始值上(因爲這是控制它的controlID),然後當它在Page_load事件中設置時,它會再次綁定它。

我建議將它綁定到可見屬性設置爲False的標籤。然後在第一個下拉selectedindex改變,設置標籤的文本屬性。

+0

你能指定那個嗎?當我第一個 開始頁面時,我沒有選擇一個值。但即使那樣,雙重約束也會發生。 – AGuyCalledGerald 2010-02-08 14:52:27

+0

@Jan:因爲你的SqlDataSource被綁定到一個ControlID,當該控件加載時,它的默認值被用來綁定SqlDataSource控件(它註冊爲導致綁定的更改)。然後當SqlDataSource加載時,它再次綁定。我寧願保持SqlDataSources不受限制,直到我真正需要它們。然後,我使用事件觸發器來更改數據源和控件ID等。 – 2010-02-08 16:00:12

0

雖然我不知道雙重綁定的確切原因,但您最好的辦法可能是爲第二個列表設置一個OnDataBinding處理程序,在其中設置一個斷點並在兩個地方檢查調用堆棧。這會告訴你爲什麼框架綁定該列表,兩次。

根據您對性能的敏感程度,您可能需要在第二個列表中將AppendDataBoundItems設置爲false,以便重新綁定它並不重要。

+0

是,you're權。 – AGuyCalledGerald 2010-02-09 18:02:50

0

嘗試包裝你的選擇中:

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

不,無論if-clause是否包含,它都會發生。 – AGuyCalledGerald 2010-02-05 13:08:26