标签:
首先在aspx界面中拖入三个DropDownList控件,分别右键属性前两个控件,把 AutoPostBack 改为 True ,Items点击添加在txt中输入请选择,并把Value的值改为0,再点击事件按钮把前两个控件添加SelectedIndexChanged事件。
数据库的设计,列名有 id(自增长) ParentId Name,如图

进入cs界面,在Page_Load中写如下代码
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
getProdata();//省(直辖市)
getcitydata();//市
getquxiandata();//县
}
}
然后在前两个DropDownList控件下写SelectedIndexChanged事件,代码如下
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
getcitydata();//市
getquxiandata();//县
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
getquxiandata();//县
}
再写 getProdata();//省(直辖市) getcitydata();//市 getquxiandata();//县 方法的代码
public void getProdata()//省、直辖市
{
var query = dc.dt.Where(p => p.ParentId == 0);
if (query.Count() !=0)
{
DropDownList1.DataSource = query;//绑定数据之前先清除之前数据
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "id";
DropDownList1.DataBind();
}
else
{
DropDownList1.Text = "无数据";
}
}
public void getcitydata()//市
{
string name1 = DropDownList1.SelectedValue;//获取选中值的ID
var query = dc.dt.Where(p => p.ParentId == int.Parse(name1));
if (query.Count() != 0)
{
DropDownList2.DataSource = query;
DropDownList2.DataTextField = "Name";
DropDownList2.DataValueField = "id";
DropDownList2.DataBind();
}
else
{
DropDownList2.SelectedIndex = 0;
}
}
public void getquxiandata()//县
{
string name2 = DropDownList2.SelectedValue;//获取选中值的ID
var query = dc.dt.Where(p => p.ParentId == int.Parse(name2));
if (query.Count() != 0)
{
DropDownList3.DataSource = query;
DropDownList3.DataTextField = "Name";
DropDownList3.DataValueField = "id";
DropDownList3.DataBind();
}
else
{
DropDownList3.SelectedIndex = 0;
}
}
完成


标签:
原文地址:http://www.cnblogs.com/hqjy/p/4339856.html