webform基本控件-----DropDownList

把内容填进去:

private void FillNation()
    {
        DropDownList1.Items.Clear();

        //查数据
        List<Nation> list = _Context.Nation.ToList();
        //送进去---循环

        ListItem temp = new ListItem("==请选择==", "-1");
        DropDownList1.Items.Add(temp);

        foreach (Nation data in list)
        {
            ListItem li = new ListItem(data.Name, data.Code);
            DropDownList1.Items.Add(li);
        }

        //送进去---绑定

       
        DropDownList1.DataSource = list;
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "Code";
        DropDownList1.DataBind();

       // ListItem temp = new ListItem("==请选择==", "-1");
        DropDownList1.Items.Insert(0, temp);
    }

把值取出来:

        //取值---SelectedValue
        Label1.Text = DropDownList1.SelectedValue;
        //取值---SelectedItem
        Label1.Text = DropDownList1.SelectedItem.Text + DropDownList1.SelectedItem.Value;
        //取值---SelectedIndex
        Label1.Text = DropDownList1.Items[DropDownList1.SelectedIndex].Value;
        //取值---遍历
        foreach (ListItem li in DropDownList1.Items)
        {
            if (li.Selected == true)
            {
                Label1.Text = li.Text + li.Value;
            }
        }

设定某项为选中值:

        //SelectedValue
        DropDownList1.SelectedValue = TextBox1.Text;
        //SelectedIndex
        DropDownList1.SelectedIndex = Convert.ToInt32(TextBox1.Text); 
        //遍历
        DropDownList1.SelectedIndex = -1;
        foreach (ListItem li in DropDownList1.Items)
        {
            if (li.Value == TextBox1.Text)
            {
                li.Selected = true;
            }
        }

 

转载于:https://www.cnblogs.com/qianxiaojinnian/p/4718336.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值