我有两个下拉列表。第1名:ddlProvince
- 第2名:ddlCities
我在ddlProvince
填写了以下代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
dtProvince = clsD.FillDataTable("provinceFetch");//Get data using storprocedure
ddlProvince.DataSource = dtProvince;
ddlProvince.DataTextField = "pName";
ddlProvince.DataValueField = "pId";
ddlProvince.DataBind();
}
}
并填充ddlCities
使用Page_Load
中的以下代码:
if(IsPostBack)
{
ddlCity.DataSource = geo.getCities(ddlProvince.SelectedValue.ToString());
ddlCity.DataTextField = "CityName";
ddlCity.DataValueField = "CityId";
ddlCity.DataBind();
}
两个下拉列表都可以正常工作,但是当我点击按钮时,我只能从ddlCities
获得第一个值。回发后ddlCities
索引将重置为0。
我知道Button会发回一个帖子,但ddlCities
也会在回发中获取数据
这是我的aspx代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="~/UserAuthentication/Register.aspx.cs" Inherits="Register" EnableViewState="true" %>
<body>
<form class="form-horizontal" role="form" runat="server">
<div class="form-group">
<label for="country" class="col-sm-3 control-label">Province</label>
<div class="col-sm-9">
<asp:DropDownList ID="ddlProvince" runat="server" CssClass="form-control" AutoPostBack="true" ></asp:DropDownList>
</div>
</div>
<div class="form-group">
<label for="country" class="col-sm-3 control-label">City</label>
<div class="col-sm-9">
<asp:DropDownList ID="ddlCity" runat="server" CssClass="form-control" OnSelectedIndexChanged="ddlCity_SelectedIndexChanged" EnableViewState="true"></asp:DropDownList>
</div>
</div>
<asp:Button ID="btnRegister" runat="server" OnClick="btnRegister_ServerClick" class="btn btn-primary btn-lg btn-block login-button" Text="Register" />
</form>
</body>
我该如何解决这个问题?感谢。
答案 0 :(得分:2)
我建议您不要使用Page_load来加载ddlCities。而是在ddlProvince上使用该事件。有很多方法可以解决这个问题:
代码背后:
protected void itemSelected(object sender, EventArgs e)
{
ddlCity.DataSource = geo.getCities(ddlProvince.SelectedValue.ToString());
ddlCity.DataTextField = "CityName";
ddlCity.DataValueField = "CityId";
ddlCity.DataBind();
}
在您的aspx文件中:
<asp:DropDownList ID="ddlProvince" runat="server" CssClass="form-control" AutoPostBack="true" onselectedindexchanged="itemSelected"></asp:DropDownList>
您的代码有一个或其他调整,但这可以完成工作!