本文介绍了下拉列表和更新面板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我开发了地址控件,其中包含 2 个 DropDownList(用于城市和国家/地区)和几个 TextBox.第二个 DropDownList 数据源依赖于第一个 DropDownList 数据源.
<div></fieldset>
背后的代码
protected void Page_Init(object sender, EventArgs e){ddlCountry.DataBind();如果 (!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 设置为第一个(默认)值时.
我该如何避免?
解决方案
将 Page_Init
上的代码移动到 Page_Load
并放入 !IsPostBack
>
protected void Page_Load(object sender, EventArgs e){如果 (!IsPostBack){ddlCountry.DataBind();ddlCity.DataSource = Facade.Addresses.GetCities(countryId);ddlCity.DataBind();}}
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 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();
}
It works good. But if other control on the page causes PostBack, when the SelectedValue in ddlCity sets to the first (default) value.
How do I avoid it?
解决方案
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();
}
}
这篇关于下拉列表和更新面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!