ASP.NET Web Forms - SortedList 對象
ASP.NETSortedList物件表示鍵/值對的集合,這些鍵值對按鍵排序並可依照鍵和索引存取。
SortedList 物件結合了ArrayList 物件和Hashtable 物件的特性。
實例
SortedList RadiobuttonList 1
SortedList RadiobuttonList 2
SortedList DropDownList
SortedList 對象
SortedList 物件包含以鍵/值對錶示的項目。 SortedList 物件會依照字母順序或數字順序自動地對項目進行排序。
透過Add() 方法向SortedList 新增項目。透過TrimToSize() 方法把SortedList 調整為最終尺寸。
下面的程式碼建立了一個名為mycountries 的SortedList 對象,並且加入了四個元素:
<script runat="server">sub Page_Loadif Not Page.IsPostBack thendim mycountries=New SortedListmycountries.Add("N","Norway")mycountries.Add("S","Sweden")mycountries.Add("F", "France")mycountries.Add("I","Italy")end ifend sub</script>資料綁定
SortedList 物件可為下列的控制項自動產生文字和值:
asp:RadioButtonList
asp:CheckBoxList
asp:DropDownList
asp:Listbox
為了綁定資料到RadioButtonList 控件,首先要在.aspx 頁面中建立一個RadioButtonList 控制項(不帶任何asp:ListItem 元素):
<html><body><form runat="server"><asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" /></form></body></html>然後新增建立清單的腳本,並且綁定清單中的值到RadioButtonList 控制項:
<script runat="server">sub Page_Loadif Not Page.IsPostBack thendim mycountries=New SortedListmycountries.Add("N","Norway")mycountries.Add("S","Sweden")mycountries.Add("F","France")mycountries.Add("I","Italy")rb. DataSource=mycountriesrb.DataValueField="Key"rb.DataTextField="Value"rb.DataBind()end ifend sub</script><html><body><form runat="server"><asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" /></form></body></html>然後我們新增一個子例程,當使用者點擊RadioButtonList 控制項中的某個項目時,該子例程會被執行。當某個單選按鈕被點擊時,label 會出現一行文字:
實例
<script runat="server">sub Page_Loadif Not Page.IsPostBack thendim mycountries=New SortedListmycountries.Add("N","Norway")mycountries.Add("S","Sweden")mycountries.Add("F","France")mycountries.Add("I","Italy")rb. DataSource=mycountriesrb.DataValueField="Key"rb.DataTextField="Value"rb.DataBind()end ifend subsub displayMessage(s as Object,e As EventArgs)lbl1.text="Your favorite country is: " & rb.SelectedItem.Textend sub</script><html><body><form runat="server"><asp:RadioButtonList id="rb " runat="server"AutoPostBack="True" onSelectedIndexChanged="displayMessage" /><p><asp:label id="lbl1" runat="server" /></p></form></body></html>以上就是有關ASP.NETSortedList 物件的使用的內容了。