WebForm绑定省市联动
数据库
数据层
public List<addch> GetData()
{
string sql = "select * from addch where pid=0";
List<addch> list = new List<addch>();
MySqlDataReader dr = MySqlHelper.ExecuteReader(MySqlHelper.connString, CommandType.Text, sql, null);
while (dr.Read())
{
addch c = new addch();
c.Id = Convert.ToInt32(dr["Id"]);
c.Name = Convert.ToString(dr["Name"]);
if (DBNull.Value != dr["Pid"])
{
c.Pid = Convert.ToInt32(dr["Pid"]);
}
list.Add(c);
}
dr.Close();
return list;
}
public List<addch> GetDate(string StrWhere)
{
string sql = "select * from addch where pid=" + StrWhere;
List<addch> list = new List<addch>();
MySqlDataReader dr = MySqlHelper.ExecuteReader(MySqlHelper.connString, CommandType.Text, sql, null);
while (dr.Read())
{
addch c = new addch();
c.Id = Convert.ToInt32(dr["Id"]);
c.Name = Convert.ToString(dr["Name"]);
if (DBNull.Value != dr["Pid"])
{
c.Pid = Convert.ToInt32(dr["Pid"]);
}
list.Add(c);
}
dr.Close();
return list;
}
前台
<tr> <td> <span>省</span> <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"> </asp:DropDownList> </td> <td> <span>市</span> <asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="false"> </asp:DropDownList> </td> </tr>
后台
addchDAL dal = new addchDAL();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.DataSource = dal.GetData();
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Id";
DropDownList1.DataBind();
DropDownList2.DataSource = dal.GetDate(DropDownList1.SelectedValue);
DropDownList2.DataTextField = "Name";
DropDownList2.DataValueField = "Id";
DropDownList2.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList2.DataSource = dal.GetDate(DropDownList1.SelectedValue);
DropDownList2.DataTextField = "Name";
DropDownList2.DataValueField = "Id";
DropDownList2.DataBind();
}