三级连动前台代码:
<div>
省:
<asp:DropDownList ID="ddlPromary" runat="server" AutoPostBack="True" Height="16px" OnSelectedIndexChanged="ddlPromary_SelectedIndexChanged" Width="118px">
</asp:DropDownList>
市:<asp:DropDownList ID="ddlCity" runat="server" AutoPostBack="True" Height="16px" OnSelectedIndexChanged="ddlCity_SelectedIndexChanged" Width="118px">
</asp:DropDownList>
县:
<asp:DropDownList ID="ddlCount" runat="server" Height="16px" Width="118px">
</asp:DropDownList>
</div>
三级后台代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//第一次加载的时候绑定ddlPromary控件的值
string sql = "select * from province";
DataTable dt=ExecuteDataTable(sql);
ddlPromary.DataSource = dt;
ddlPromary.DataTextField = "province";
ddlPromary.DataValueField = "provinceID";
ddlPromary.DataBind();
}
}
protected void ddlPromary_SelectedIndexChanged(object sender, EventArgs e)
{
ddlCity.Items.Clear();
string sql = "select * from city where father=@id";
DataTable dt = ExecuteDataTable(sql, new SqlParameter("@id",ddlPromary.SelectedValue.ToString()));
ddlCity.DataSource = dt;
ddlCity.DataTextField = "city";
ddlCity.DataValueField = "cityID";
ddlCity.DataBind();
}
protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
{
ddlCount.Items.Clear();
string sql = "select * from area where father=@areaID";
DataTable dt = ExecuteDataTable(sql, new SqlParameter("@areaID", ddlCity.SelectedValue.ToString()));
ddlCount.DataSource = dt;
ddlCount.DataTextField = "area";
ddlCount.DataValueField = "areaID";
ddlCount.DataBind();
}
//定义一个方法,传入两个参数,一个为SQL语句,另一个是SQL语句的参数
public static DataTable ExecuteDataTable(string sql, params SqlParameter[] pms)
{
string constr = @"data source=.;initial catalog=PromaryCityCount;user id=sa;password=111111;";
SqlConnection conn = new SqlConnection(constr);
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
conn.Close();
conn.Dispose();
}