三级联动---DropDownList控件

时间:2023-03-09 00:54:49
三级联动---DropDownList控件
AutoPostBack属性:意思是自动回传,也就是说此控件值更改后是否和服务器进行交互
比如Dropdownlist控件,若设置为True,则你更换下拉列表值时会刷新页面(如果是网页的话),设置为flase就不会刷新了(也就是false时不和服务器交互) 列如:要操作ChinaStates表, 先连接数据库--三大类,ChinaDA类:如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient; /// <summary>
/// ChinaDA 的摘要说明
/// </summary>
public class ChinaDA
{
private SqlConnection _conn ;
private SqlCommand _cmd;
private SqlDataReader _dr;
public ChinaDA()
{
_conn = new SqlConnection("server=.;database=mydb;user=sa;pwd=100867");
_cmd = _conn.CreateCommand();
} public List<ChinaStates> Select(string PC)//只查询 父级(parentareacode)
{
_cmd.CommandText = "select * from ChinaStates where ParentAreaCode=@parentareacode";
_cmd.Parameters.Add("@parentareacode",PC);
_conn.Open();
_dr = _cmd.ExecuteReader();
List<ChinaStates> list = new List<ChinaStates>();
if (_dr.HasRows)
{
while (_dr.Read())
{
ChinaStates cs = new ChinaStates();
cs.AreaCode=_dr[].ToString();
cs.AreaName=_dr[].ToString();
cs.ParentAreaCode=_dr[].ToString();
list.Add(cs);
}
}
_conn.Close();
return list;
}
}

 aspx.cs里:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; public partial class sanji : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{//下面做了方法来这里调用,调用三次
Bind(DropDownList1,new ChinaDA().Select(""));//中国下的
Bind(DropDownList2,new ChinaDA().Select(DropDownList1.SelectedValue));//取省下面的值
Bind(DropDownList3,new ChinaDA().Select(DropDownList2.SelectedValue));//取市下面的值 }
DropDownList1.SelectedIndexChanged += DropDownList1_SelectedIndexChanged;//做委托
DropDownList2.SelectedIndexChanged += DropDownList2_SelectedIndexChanged;
} void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
// 列表控件里的值在信息发往服务器时发生的变化,
Bind(DropDownList3, new ChinaDA().Select(DropDownList2.SelectedValue));//取市下面的值-区
} void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Bind(DropDownList2, new ChinaDA().Select(DropDownList1.SelectedValue));//取省下面的值-市
Bind(DropDownList3, new ChinaDA().Select(DropDownList2.SelectedValue));//取市下面的值-区
} //填充三个下拉的内容,做集合 绑定数据
private void Bind(DropDownList dd1, List<ChinaStates> list)
{
dd1.DataSource = list;
dd1.DataTextField = "AreaName";
dd1.DataValueField = "AreaCode";
dd1.DataBind();//绑定到...
} }