ArrayList 對象是包含單一數據值的項目的集合。
ASP NET - ArrayList 對象
實例
ArrayList DropDownList
ArrayList RadioButtonList
創建 ArrayList
ArrayList 對象是包含單一數據值的項目的集合。
通過 Add() 方法向 ArrayList 添加項目。
下面的代碼創建了一個新的 ArrayList 對象,名為 mycountries,并添加了四個項目:
<script runat="server"> Sub Page_Load if Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("China") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") end if end sub </script>
默認地,一個 ArrayList 對象包含 16 個條目。可通過 TrimToSize() 方法把 ArrayList 調整為最終大小:
<script runat="server"> Sub Page_Load if Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("China") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") mycountries.TrimToSize()
end if end sub </script>
通過 Sort() 方法,ArrayList 也能夠按照字母順序或者數字順序進行排序:
<script runat="server"> Sub Page_Load if Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("China") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") mycountries.TrimToSize() mycountries.Sort()
end if end sub </script>
要實現顛倒的排序,請在 Sort() 方法后應用 Reverse() 方法:
<script runat="server"> Sub Page_Load if Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("China") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") mycountries.TrimToSize() mycountries.Sort() mycountries.Reverse()
end if end sub </script>
把數據綁定到 ArrayList
ArrayList 對象可向下面這些控件自動地生成文本和值:
- asp:RadioButtonList
- asp:CheckBoxList
- asp:DropDownList
- asp:Listbox
如需把數據綁定到一個 RadioButtonList 控件,首先請在一個 .aspx 頁面中創建 RadioButtonList 控件(請注意,沒有任何 asp:ListItem 元素):
<html> <body> <form runat="server"> <asp:RadioButtonList id="rb" runat="server" /> </form> </body> </html>
然后添加構建列表的腳本,并把列表中的值綁定到該 RadioButtonList 控件:
<script runat="server"> Sub Page_Load if Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("China") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") mycountries.TrimToSize() mycountries.Sort() rb.DataSource=mycountries rb.DataBind()
end if end sub </script> <html> <body> <form runat="server"> <asp:RadioButtonList id="rb" runat="server" /> </form> </body> </html>
顯示這個例子
RadioButtonList 控件的 DataSource 屬性被設置為該 ArrayList,它定義了這個 RadioButtonList 控件的數據源。RadioButtonList 控件的 DataBind() 方法把 RadioButtonList 控件與數據源綁定在一起。
注釋:數據值作為控件的 Text 和 Value 屬性來使用。如需添加不同于 Text 的 Value,既可以使用 Hashtable 對象,也可以使用 SortedList 對象。