前台:
<body>
<form id="form1" runat="server">
<div>
<div style="float:left; margin-left:100px;">
<asp:DropDownList ID="DropDownListProvince" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownListProvince_SelectedIndexChanged">
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
</div>
<div style="float:left; margin-left:100px;">
<asp:DropDownList ID="DropDownListCity" runat="server">
</asp:DropDownList>
</div>
</div>
</form>
</body>
后台:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string sql = "select * from province";
DataTable dt = SQLHelper.ExecuteDataTable(sql);
this.DropDownListProvince.DataSource = dt;
this.DropDownListProvince.DataValueField = "PId";
this.DropDownListProvince.DataTextField = "Provinces";
this.DropDownListProvince.DataBind();
}
}
protected void DropDownListProvince_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownListCity.Items.Clear();
int dr =int.Parse(DropDownListProvince.SelectedValue);
string sql="select * from city where PId=@pid";
SqlParameter[] pms = new SqlParameter[] { new SqlParameter("@pid", dr) };
DataTable dt=SQLHelper.ExecuteDataTable(sql,pms);
this.DropDownListCity.DataSource = dt;
this.DropDownListCity.DataValueField = "CId";
this.DropDownListCity.DataTextField = "Citys";
this.DropDownListCity.DataBind();
}
注:在省市级联里,一定要注意两个知识点,1、!IsPostBack 2、设置省DropDownList的AutoPostBack="True";