ASP.NET - Objek ArrayList
- 上一页 WebForms 数据绑定
- 下一页 Hashtable WebForms
Objek ArrayList adalah kumpulan projek yang mengandungi nilai data tunggal.
Mencipta ArrayList
Objek ArrayList adalah kumpulan projek yang mengandungi nilai data tunggal.
Menambah projek kepada ArrayList melalui method Add()
Kod di bawah ini mencipta objek ArrayList baru bernama mycountries dan menambah empat projek:
<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>
Secara lalai, objek ArrayList mengandungi 16 entiti. Dapat diubah saiz kepada saiz akhir dengan TrimToSize() method:
<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>
Dengan Sort() method, ArrayList juga boleh diurutkan mengikut abjad atau angka:
<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>
Untuk mencapai pengurutan terbalik, laporkan Reverse() method selepas Sort() method:
<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>
Memikat data kepada ArrayList
Objek ArrayList boleh secara automatik menghasilkan teks dan nilai untuk kawalan di bawah ini:
- asp:RadioButtonList
- asp:CheckBoxList
- asp:DropDownList
- asp:Listbox
Jika perlu memikat data kepada kawalan RadioButtonList, pertama-tama sila cipta kawalan RadioButtonList di halaman .aspx (perhatikan, tiada sebarang elemen 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 对象。
- 上一页 WebForms 数据绑定
- 下一页 Hashtable WebForms