DropDownList控件又稱下拉列表框控件, 控件 列表 中的多行數(shù) 據(jù) 以隱含 的形式表 示 出 來,當(dāng)用戶需要選擇所需列表項時,通過點擊 “下三角 ”圖形 展示 ,用戶每次 只能選用一個 數(shù)據(jù)項。DropDownList控件實際上是列表項 的 容器 ,下拉列表框 用 Items集合表示各項 的內(nèi) 容。如果在 ASP.NET頁面中逐個 的手 動填寫 DropDownList控件的列表選項,當(dāng)列表項很多 的時候會 比較繁瑣 ,而且修改 比較麻煩 。 DropDownList控件動態(tài)連接到數(shù)據(jù)庫,按指定 條件從數(shù)據(jù)庫 中查詢 出列表選項數(shù)據(jù),然后綁 定到控件,可以方便快速地顯示出多個下拉選 項 。 同時 ,通過修 改數(shù)據(jù)庫 中數(shù)據(jù) ,可 以動 態(tài)改 變下 拉選項。例如 ,在導(dǎo) 師遴 選系統(tǒng) 中, 研究生導(dǎo)師填寫申請信息 的時候 ,需要選 擇申 請類型,而且同樣的信息在多處頁面出現(xiàn),將 數(shù)據(jù)庫中申請類型表的數(shù)據(jù)綁定到 DropDownList控件上,能比較好的解決問題。
接下來給大家介紹C#使用DropDownList綁定添加新數(shù)據(jù)的方法,具體內(nèi)容如下所示:
第一種:在前臺手動綁定(適用于固定不變的數(shù)據(jù)項)
1
2
3
4
5
6
|
<asp:DropDownList ID= "DropDownList1" runat= "server" > <asp:ListItem Value= "1" >南京</asp:ListItem> <asp:ListItem Value= "2" >揚州</asp:ListItem> <asp:ListItem Value= "3" >徐州</asp:ListItem> <asp:ListItem Value= "4" >蘇州</asp:ListItem> </asp:DropDownList> |
第二種:在后臺動態(tài)綁定
1
2
3
4
5
6
7
|
DataTable dt = new DataTable (); //中心思想就是將下拉列表的數(shù)據(jù)源綁定一個表(這里沒有對表進行賦值) DropDownList1.DataSource = dt.DefaultView; //設(shè)置DropDownList空間顯示項對應(yīng)的字段名,假設(shè)表里面有兩列,一列綁定下拉列表的Text,另一列綁定Value DropDownList1.DataValueField = dt.Columns[0].ColumnName; DropDownList1.DataTextField = dt.Columns[1].ColumnName; DropDownList1.DataBind(); |
第三種:自定義添加
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
//方法一:分步進行 ListItem li = new ListItem(); li.Text = "南京" ; li.Value = "1" ; DropDownList1.Items.Add(li); //方法二:ListItem()第一個參數(shù)是Text的值,第二個參數(shù)是Value的值 ListItem li = new ListItem( "揚州" , "2" ); DropDownList1.Items.Add(li); //方法三:一步到位 DropDownList1.Items.Add( new ListItem( "徐州" , "3" )); //方法四:(循環(huán)添加) string [] city={ "南京" , "揚州" , "徐州" , "蘇州" }; for ( int i=0;i<city.Length;i++) { DropDownList1.Items.Insert(i,city[i]); DropDownList1.Items[i].Value = i.ToString(); } |
以上內(nèi)容給大家介紹了C#使用DropDownList綁定添加新數(shù)據(jù)的方法匯總,希望對大家有所幫助!