绑定数据
设置DropDownList值绑定DataTablepublic 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();}}
单个添加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")));}
拼接字符串
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>
设置默认选中的值
DropDownList.Items[i].Selected = true;DropDownList.Items.FindByText(“123”).Selected = true;DropDownList.Items.FindByValue(“123”).Selected = true;js设置选中网上好多,百度吧