欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

asp:DropDownList动态绑定数据,设置默认值

程序员文章站 2022-06-11 22:46:15
...

绑定数据

  1. 设置DropDownList值绑定DataTable
        public void BindDropDownList(DropDownList ddlList)
        {
            ddlList.Items.Clear();
            var dt = new DataTable(); // 获取数据自己写
            if (dt != null && dt.Rows.Count > 0)
            {
                ddlList.DataSource = dt;
                ddlList.DataTextField = "DeptName"; // DeptName:dt中列名
                ddlList.DataValueField = "DeptCode";// DeptCode中列名
                ddlList.DataBind();
            }
        }
  1. 单个添加ListItem
        public void BindDropDownList(DropDownList ddlList,string datenow = null)
        {
            if (!string.IsNullOrEmpty(datenow))
            {
                ListItem li = new ListItem(datenow, datenow);
                li.Selected = true;
                ddlList.Items.Add(li);
            }
            ddlList.Items.Add(new ListItem(DateTime.Now.AddMonths(-1).ToString("yyyyMM"), DateTime.Now.AddMonths(-1).ToString("yyyyMM")));
            ddlList.Items.Add(new ListItem(DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyyMM")));
            ddlList.Items.Add(new ListItem(DateTime.Now.AddMonths(1).ToString("yyyyMM"), DateTime.Now.AddMonths(-1).ToString("yyyyMM")));
        }
  1. 拼接字符串
        public string BindDropDownList(bool IsHavePleaseSelect)
        {
            var dt = new DataTable(); // 获取数据自己写
            if (dt != null && dt.Rows.Count > 0)
            {
                string r = string.Empty;
                if (IsHavePleaseSelect)
                {
                    r = "<OPTION value='请选择...' selected>请选择...</OPTION>";
                }
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    r += "<OPTION value='" + dt.Rows[i]["Code"].ToString() + "'>" + dt.Rows[i]["DictItem"].ToString() + "</OPTION>";
                }
                    return r;
            }
            else
            {
                return string.Empty;
            }
        }

// 引用
string DropDownListString = BindDropDownList();

然后在aspx页面

<select name="DropDownList">
    <%=DropDownListString%>
</select>

设置默认选中的值

  1. DropDownList.Items[i].Selected = true;
  2. DropDownList.Items.FindByText(“123”).Selected = true;
  3. DropDownList.Items.FindByValue(“123”).Selected = true;
  4. js设置选中
    网上好多,百度吧
相关标签: dropdownlist asp