DropDownList的用法
DropDownList是一個下拉列表菜單,平時我們也會經(jīng)常用到,下面就來看看如何綁定值
1>???? 靜態(tài)添加,就是說在值都很明確的情況下
ListItem list1 = new ListItem("a","1");
ListItem list2 = new ListItem("b", "2");
ListItem list3 = new ListItem("c", "3");
ListItem list4 = new ListItem("d", "4");
this.DropDownList2.Items.Add(list1);
this.DropDownList2.Items.Add(list2);
this.DropDownList2.Items.Add(list3);
this.DropDownList2.Items.Add(list4);
如果是要特別放置,明確每個的具體索引,我們可以采用insert方法添加
This.DropDownList2.Items.insert(int index,Listitem item)
也可以在后臺html直接添加:
<asp:DropDownList ID="DropDownList2" runat="server"? >
<asp:ListItem Value="1">a</asp:ListItem>
<asp:ListItem Value="2">b</asp:ListItem>
<asp:ListItem Value="3">c</asp:ListItem>
<asp:ListItem Value="4">d</asp:ListItem>
</asp:DropDownList>
轉(zhuǎn)為html就是
<select id="select">
<option value="1">a</option>
<option value="2">a</option>
<option value="3">a</option>
<option value="4">a</option>
</select>
?
2>???? 動態(tài)綁定
@ 視圖綁定
?
<asp:DropDownList ID="DropDownList1" runat="server"
DataTextField="Name" DataValueField="Id">
</asp:DropDownList>
<asp:ObjectDataSource ID="ObjectDataSource2" runat="server"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetAllUser"
TypeName="MyBookShop.BLL.UserManager"></asp:ObjectDataSource>
這樣綁定唯一不好的一點就是無法再第一個列表中顯示“—請選擇—”
@? 代碼綁定
這種綁定方式非常靈活,也能很好的解決上面的問題,下面就來看看如何綁定
this.DropDownList1.DataSource = UserManager.GetAllUser();
this.DropDownList1.DataBind();
具體有兩種方法:
1? ?ListItem list = new ListItem("--請選擇--","0");
this.DropDownList1.DataSource = UserManager.GetAllUser();
this.DropDownList1.Items.Insert(0, list);
this.DropDownList1.DataTextField = "name";
this.DropDownList1.DataValueField = "id";
this.DropDownList1.DataBind();
???? 但是當我綁定是DataSet的時候,上面那樣寫的話就沒有加上("--請選擇--"),這個要放在下面寫才可以,如
???? ?protected void LinkBind()
??? {
??????? DataSet ds = linkManager.GetList(" jh_checked='是'");
??????? DroUrl.DataSource = ds;
??????? DroUrl.DataTextField = "jh_linkname";
??????? DroUrl.DataValueField = "jh_linkurl";
??????? DroUrl.DataBind();
??????? ListItem item = new ListItem("--請選擇---", "#");
??????? DroUrl.Items.Insert(0,item);
??? }
2????? IList<DepartInfo> departList = DepartInfoManager.GetDepartList();
departList.Insert(0, new DepartInfo { DepartId = 0, DepartName = "--請選擇--" });
ddDepart.DataSource = departList;
ddDepart.DataTextField = "DepartName";
ddDepart.DataValueField = "DepartId";
ddDepart.DataBind();
平時我們會在友情鏈接中使用,選擇一項的時候鏈接會改變,而且打開一個新的頁面,這個很好實現(xiàn)
?? protected void DropDownList1_TextChanged(object sender, EventArgs e)
???? ? {
??????? string link = this.DropDownList1.SelectedValue;
??????? Response.Write("<script>window.open('"+link+"','_Blank')</script>");
?????? }
靈活掌握就可以了
?
?
與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的DropDownList的用法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C/C++面试题:什么是COM和Acti
- 下一篇: 终端服务器超过了 最大连接数