20151214下拉列表:DropDownList

注意:
    1.如果用事件的话就要把控件的AutoPostBack设置成true
    2.防止网页刷新用一个判断    if (!IsPostBack)//判断是第一个开始还是取的返回值
                                {
                                }

下拉列表:DropDownList
    1.绑定数据:
          //指定数据源
             DropDownList1.DataSource = context.Nation;
             DropDownList1.DataValueField = "Code";
             DropDownList1.DataTextField = "Name";
        //绑定数据源
             DropDownList1.DataBind();


        //新建一个集合,往dropdownlist里面添加集合
            ListItem item = new ListItem();
            item.Text = "中国";
            item.Value = "0001";
            DropDownList1.Items.Add(item);

        也可以在dropdownlist上面选择数据源

    2.取选中项的值
        DropDownList1.SelectedValue.ToString();

    3.设置哪一项选中
        DropDownList1.SelectedIndex = 2;

        //便利
            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 == "0001");
        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();
    }
原文地址:https://www.cnblogs.com/hz1234/p/5095075.html