本文介绍了DropDownList的和更新面板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我开发地址控制,其中包含2 DropDownLists(城市和国家)和一些文本框。第二个DropDownList的数据源取决于第一个DropDownList的数据源。
I develop address control, which contains 2 DropDownLists (for cities and countries) and several TextBoxes. The second DropDownList DataSource depends on the first DropDownList DataSource.
<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>
code
Code Behind
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();
}
它的工作原理很好。但是,如果页面上的其他控件导致回传,当ddlCity的的SelectedValue设置为第一个(默认)值。
It works good. But if other control on the page causes PostBack, when the SelectedValue in ddlCity sets to the first (default) value.
我如何避免呢?
推荐答案
将code对 Page_Init
到的Page_Load
,并把它里面!的IsPostBack
Move the code on Page_Init
to Page_Load
and put it inside !IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlCountry.DataBind();
ddlCity.DataSource = Facade.Addresses.GetCities(countryId);
ddlCity.DataBind();
}
}
这篇关于DropDownList的和更新面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!