ASP.NET Web Forms – ArrayList 對象簡介

ArrayList 對象是包含單個數據值的項目的集合。

ASP.NET Web Forms – ArrayList 對象簡介ASP.NET Web Forms – ArrayList 對象簡介

創建 ArrayList

ArrayList 對象是包含單個數據值的項目的集合。

通過 Add() 方法向 ArrayList 添加項目。

下面的代碼創建了一個名爲 mycountries 的 ArrayList 對象,並添加了四個項目:

<script runat="server">
Sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New ArrayList
mycountries.Add("Norway")   
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("Norway")   
mycou
ntries.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("Norway") 
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("Norway")  
mycountries.Add("Sweden")   
mycountries.Add("France")   
mycountries.Add("Italy")   
mycountries.TrimToSize()   
mycountries.Sort()
mycountries.Reverse()
end if
end sub
</script>
綁定數據到 ArrayList

ArrayList 對象可爲下列的控件自動生成文本和值:

  1. asp:RadioButtonList
  2. asp:CheckBoxList
  3. asp:DropDownList
  4. 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("Norway")
  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 對象。

本文地址:https://www.linuxprobe.com/web-forms-arraylist.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章