ASP.NET - Objek SortedList
- 上一页 Hashtable WebForms
- 下一页 Fail XML WebForms
Objek SortedList mempunyai sifat keduanya ArrayList dan Hashtable objek.
Objek SortedList
Objek SortedList mengandung item yang diwakili dengan pasangan kunci/nilai. Objek SortedList dapat mengurutkan item secara otomatis berdasarkan urutan karakter atau numerik.
Tambahkan item ke SortedList melalui metode Add(). SortedList dapat disesuaikan ukurannya akhir melalui metode TrimToSize().
Kode di bawah ini menciptakan objek SortedList bernama mycountries dan menambahkan empat elemen:
<script runat="server"> sub Page_Load if Not Page.IsPostBack then dim mycountries=New SortedList mycountries.Add("C","China") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") end if end sub </script>
Pengikat Data
Objek SortedList dapat secara otomatis mengenerate teks dan nilai untuk kontrol di bawah ini:
- asp:RadioButtonList
- asp:CheckBoxList
- asp:DropDownList
- asp:Listbox
Untuk memikat data ke kontrol RadioButtonList, pertama-tama buat sebuah kontrol RadioButtonList di berkas aspx (tanpa elemen asp:ListItem):
<html> <body> <form runat="server"> <asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" /> </form> </body> </html>
kemudian tambahkan skrip untuk membangun senarai:
<script runat="server"> sub Page_Load if Not Page.IsPostBack then dim mycountries=New SortedList mycountries.Add("C","China") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") rb.DataSource=mycountries rb.DataValueField="Key" rb.DataTextField="Value" rb.DataBind() end if end 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_Load if Not Page.IsPostBack then dim mycountries=New SortedList mycountries.Add("C","China") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") rb.DataSource=mycountries rb.DataValueField="Key" rb.DataTextField="Value" rb.DataBind() end if end sub sub displayMessage(s as Object,e As EventArgs) lbl1.text="Your favorite country is: " & rb.SelectedItem.Text end 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>
- 上一页 Hashtable WebForms
- 下一页 Fail XML WebForms