2011-07-21 83 views
2

我開發了地址控件,其中包含2個DropDownLists(適用於城市和國家)和幾個TextBoxes。第二個DropDownList數據源依賴於第一個DropDownList數據源。DropDownList和更新面板

<fieldset> 
<legend><%=Title%></legend> 
    <asp:UpdatePanel ID="UpdatePanel1" runat="server"> 
    <ContentTemplate> 
     <div> 
      <label for="<%=ddlCountry.ClientID %>">Country</label> 
      <asp:DropDownList runat="server" ID="ddlCountry" 
       DataTextField="Name" DataValueField="Id" 
       DataSource="<%#Facade.Addresses.GetCountries() %>" 
       AutoPostBack="true" 
       OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged" 
      /> 
     </div> 
     <div> 
      <label for="<%=ddlCity.ClientID %>">City</label> 
      <asp:DropDownList runat="server" ID="ddlCity" 
       DataTextField="Name" DataValueField="Name" /> 
     </div> 
    </ContentTemplate> 
    <Triggers> 
     <asp:AsyncPostBackTrigger ControlID="ddlCountry" EventName="SelectedIndexChanged" /> 
    </Triggers> 
</asp:UpdatePanel> 
<div> 
    <label for="<%=txtStreet.ClientID %>">Street</label> 
    <uc:TextBox ID="txtStreet" Text="<%#Address.Street %>" runat="server" /> 
</div> 
<div> 
    <label for="<%=txtBlock.ClientID %>">Block</label> 
    <uc:TextBox ID="txtBlock" Text="<%#Address.Block %>" runat="server" /> 
</div> 
<div> 
</fieldset> 

代碼隱藏

protected void Page_Init(object sender, EventArgs e) 
    { 

    ddlCountry.DataBind(); 
    if (!IsPostBack) 
     { 
     ddlCity.DataSource = Facade.Addresses.GetCities(countryId); 
     ddlCity.DataBind(); 
     } 

} 

protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e) 
    { 
    ddlCity.DataSource = Facade.Addresses.GetCities(countryId); 
    ddlCity.DataBind(); 
} 

它的工作原理好。但是,如果頁面上的其他控件導致PostBack,則ddlCity中的SelectedValue將設置爲第一個(默認)值。

我該如何避免它?

+0

法赫德有解決方案。 naveen的建議只是爲了符合標準,儘管您只需要!IsPostback – rkw

回答

3

繼續前行Page_Init代碼Page_Load並把它內部!IsPostBack

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) 
    { 
     ddlCountry.DataBind(); 
     ddlCity.DataSource = Facade.Addresses.GetCities(countryId); 
     ddlCity.DataBind(); 
    } 
} 
+0

爲什麼要檢查「IsPostBack」兩次? – Alexandre

+0

oops。更新的代碼 – naveen

0

放ddlCountry.DataBind();裏面如果條件