注意:
.如果用事件的话就要把控件的AutoPostBack设置成true
.防止网页刷新用一个判断 if (!IsPostBack)//判断是第一个开始还是取的返回值
{
}
下拉列表:DropDownList
.绑定数据:
//指定数据源
DropDownList1.DataSource = context.Nation;
DropDownList1.DataValueField = "Code";
DropDownList1.DataTextField = "Name";
//绑定数据源
DropDownList1.DataBind();
//新建一个集合,往dropdownlist里面添加集合
ListItem item = new ListItem();
item.Text = "中国";
item.Value = "";
DropDownList1.Items.Add(item);
也可以在dropdownlist上面选择数据源
.取选中项的值
DropDownList1.SelectedValue.ToString();
.设置哪一项选中
DropDownList1.SelectedIndex = ;
//便利
foreach (ListItem item in DropDownList1.Items)
{
if (item.Value == "n002")
{
item.Selected = true;
}
}
三级联动
private DataClassesDataContext context = new DataClassesDataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillSheng();
FillShi();
FillQu();
}
}
public void FillSheng()
{
DropDownList1.DataSource = context.ChinaStates.Where(r => r.ParentAreaCode == "");
DropDownList1.DataValueField = "AreaCode";
DropDownList1.DataTextField = "AreaName";
DropDownList1.DataBind();
}
public void FillShi()
{
string sheng = DropDownList1.SelectedValue.ToString();
DropDownList2.DataSource = context.ChinaStates.Where(r => r.ParentAreaCode == sheng);
DropDownList2.DataValueField = "AreaCode";
DropDownList2.DataTextField = "AreaName";
DropDownList2.DataBind();
}
public void FillQu()
{
string shi = DropDownList2.SelectedValue.ToString();
DropDownList3.DataSource = context.ChinaStates.Where(r => r.ParentAreaCode == shi);
DropDownList3.DataValueField = "AreaCode";
DropDownList3.DataTextField = "AreaName";
DropDownList3.DataBind();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
FillShi();
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
FillQu();
}