ASP.NET中中DropDownList下拉框列表控件绑定数据的下拉框列表控件绑定数据的4种方种方
法法
本文主要介绍了DropDownList控件4种绑定数据的基础用法,希望对大家能有所帮助。
DropDownList Web 服务器控件使用户能够从预定义的列表中选择一项。它与 ListBox Web 服务器控件的不同之处在于,其项
列表在用户单击下拉按钮之前一直处于隐藏状态。另外,DropDownList 控件与 ListBox 控件的不同之处还在于它不支持多重
选择模式。
DropDownList在html中的呈现对应的是select,下面让我们来看一下DropDownList绑定数据的几种方法。
一、把一、把Array数组绑到数组绑到DropDownList
复制代码 代码如下:
string[] Month =new string[7]{ "January", "February", "March", "April", "May", "June", "July" };
this.DropDownList1.DataSource = Month;
this.DropDownList1.DataBind();
这种方法只可以绑定一组数据到DropDownList,因为DropDownList可以绑定两种数据:1是DataTextField、2是
DataValueField,所以第一种方法绑定后DataTextField的值==DataTextField值。
二、把动态二、把动态Array数组绑定到数组绑定到DropDownList
复制代码 代码如下:
ArrayList ar = new ArrayList();
for (int i = 1; i <=12; i++)
{
ar.Add(i+"月");
}
this.DropDownList2.DataSource = ar;
this.DropDownList2.DataBind();
本质上就是讲1到12月加到数组中,如下:
复制代码 代码如下:
ArrayList ar = new ArrayList();
ar.Add("1月");
ar.Add("2月");
ar.Add("3月");
ar.Add("4月");
...
this.DropDownList2.DataSource = ar;
this.DropDownList2.DataBind();
这种方法的好处是通过ArrayList.Add的方法,可以实现动态添加元素的功能,比方说,有一个DataTable,我们要把DataTable
中一行的数据读出来添加到Arraylist当中。
看我以下的示的代码
复制代码 代码如下:
ArrayList ar = new ArrayList();
DataTable dt=dataset.Tables[0]
foreach (DataRow dr in dt.Rows)
{
ar.Add(dr[0].ToString());
}
以上代码从一个DataTable中通过foreach语句循环读取Table中一行数据中第一个格的值添加到ArrayList当中。
三、将三、将Hashtable绑定到绑定到Dropdownlist当中当中Hashtable的方法的好处是,它也可以绑定两种数据一个是的方法的好处是,它也可以绑定两种数据一个是"key,一个是一个是"value",
这样的话,我们就可以为这样的话,我们就可以为dropdonwlist绑定上两种不同的数据了。绑定上两种不同的数据了。
复制代码 代码如下:
评论0