本文主要是介绍【转载百度经验】DropDownList控件赋值,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
DropDownList控件赋值简而言之,就是取出数据,通过DropDownList.Items.Add(),循环赋值。具体步骤如下:
①根据业务查出DropDownList控件的DataSet,从DataSet实例中取出DataTable。
②然后循环遍历DataTable的DataRow,从对应的DataRow对象中取出要显示的字段和序列的字段,创建new ListItem(显示的字段, 序列的字段)创建ListItem对象。
③设定DropDownList.Items.Add(ListItem对象)方法。
实际例子:
①取出DataSet
#region 页面加载时新闻类别绑定
/// <summary>
/// 页面加载时新闻类别绑定
/// </summary>
private void DropDownList_ArticleClass_DataBind()
{
Maticsoft.BLL.job_news_category bll_tb_articleclass = new Maticsoft.BLL.job_news_category();
DataSet ds = bll_tb_articleclass.GetAllList();
DataTable dt = ds.Tables[0];
LTP.Common.PublicFc.DropList_Bind1(dt, DropDownList_catid);
}
#endregion
②条件满足parentid=0的数据赋值给DropDownList
#region 新闻分层显示类别层次
/// <summary>
/// 可选父类显示
/// </summary>
public static void DropList_Bind1(DataTable dt, DropDownList dropDownList)
{
dropDownList.Items.Clear();
if(dropDownList.ID == "DropDownList_catid")
{
dropDownList.Items.Add(new ListItem("不限类别", "0"));
}
else
{
dropDownList.Items.Add(new ListItem("顶级根类", "0"));
}
DataRow[] drs;
drs = dt.Select("parentid=0", "catid ASC");
if (drs.Length > 0)
{
foreach (DataRow dr in drs)
{
string className = "╋" + dr["catName"].ToString();
string valueID = dr["catid"].ToString();
int fatherID = int.Parse(valueID);
dropDownList.Items.Add(new ListItem(className, valueID));
ChileNodeBind1(fatherID, dt, System.Web.HttpContext.Current.Server.HtmlDecode(" "), dropDownList);
}
}
}
③条件满足"parentid=" + fatherID, "catid ASC"的数据赋值给DropDownList
private static void ChileNodeBind1(int fatherID, DataTable dt, string prefix, DropDownList dropDownList)
{
DataRow[] drs;
drs = dt.Select("parentid=" + fatherID, "catid ASC");
if (drs.Length > 0)
{
foreach (DataRow dr in drs)
{
string className = prefix + "『" + dr["catname"].ToString() + "』";
string valueID = dr["catid"].ToString(); fatherID = int.Parse(valueID); dropDownList.Items.Add(new ListItem(className, valueID));
//prefix = System.Web.HttpContext.Current.Server.HtmlDecode(" ") + prefix;
ChileNodeBind1(fatherID, dt, prefix, dropDownList);
}
}
}
#endregion
这篇关于【转载百度经验】DropDownList控件赋值的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!