ASP.NET - ArrayList-objekt

ArrayList-objekt är en samling av poster som innehåller en enskild datavärde.

Exempel

ArrayList DropDownList

ArrayList RadioButtonList

Skapa ArrayList

ArrayList-objekt är en samling av poster som innehåller en enskild datavärde.

Lägg till poster till ArrayList med Add()-metoden.

Följande kod skapar ett nytt ArrayList-objekt vid namn mycountries och lägger till fyra poster:

<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>

Som standard innehåller ett ArrayList-objekt 16 poster. Du kan justera ArrayList till den slutliga storleken med TrimToSize()-metoden:

<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>

Genom Sort()-metoden kan ArrayList också sortera efter bokstavsordning eller numerisk ordning:

<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>

För att uppnå omvänd sortering, tillämpa Reverse()-metoden efter Sort()-metoden:

<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>

Binda data till ArrayList

ArrayList-objekt kan automatiskt generera text och värden för följande kontroller:

  • asp:RadioButtonList
  • asp:CheckBoxList
  • asp:DropDownList
  • asp:Listbox

För att binda data till en RadioButtonList-kontroll, skapa först en RadioButtonList-kontroll i en .aspx-sida (observera, det finns inga asp:ListItem-element):

<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 对象。