国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

ASP.NET中DropDownList下拉框列表控件綁定數據的4種方法

2024-07-10 12:47:20
字體:
來源:轉載
供稿:網友

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綁定上兩種不同的數據了。

代碼如下:
Hashtable Ht = new Hashtable();
Ht.Add("January", "1月");
Ht.Add("February", "2月");
Ht.Add("March", "3月");
Ht.Add("April", "4月");
Ht.Add("May", "5月");
Ht.Add("June", "6月");
Ht.Add("July", "7月");
this.DropDownList3.DataSource = Ht;
this.DropDownList3.DataValueField = "key";
this.DropDownList3.DataTextField = "value";
this.DropDownList3.DataBind();

四、把Object對象綁定到dropdownlist

首先新增一個類,結構如下

代碼如下:
public class ClassMonth
{
    private string _MonthEN = DateTime.Now.ToString("MMMM",System.Globalization.CultureInfo.CreateSpecificCulture("en"));

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宜君县| 玉林市| 凤山市| 承德市| 龙江县| 温宿县| 铁岭县| 察雅县| 金湖县| 麻城市| 类乌齐县| 文水县| 怀宁县| 荣成市| 垫江县| 拜泉县| 交口县| 迁安市| 大姚县| 青浦区| 岳西县| 腾冲县| 镇沅| 凤山县| 万安县| 定日县| 达尔| 七台河市| 盐边县| 平顶山市| 西乌| 贵港市| 永康市| 科尔| 绥宁县| 康平县| 高州市| 宜宾市| 沽源县| 武川县| 班戈县|