ASP.NET - SortedList object
- Previous Page WebForms Hashtable
- Next Page WebForms XML File
The SortedList object has the characteristics of both ArrayList and Hashtable objects.
SortedList object
The SortedList object contains items represented by key/value pairs. The SortedList object can automatically sort the items in alphabetical or numerical order.
Items are added to the SortedList through the Add() method. The SortedList can be adjusted to the final size with the TrimToSize() method.
The following code creates a SortedList named mycountries and adds four elements:
<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>
Data binding
The SortedList object can automatically generate text and values for the following controls below:
- asp:RadioButtonList
- asp:CheckBoxList
- asp:DropDownList
- asp:Listbox
To bind data to the RadioButtonList control, first create a RadioButtonList control in the aspx file (without any asp:ListItem elements):
<html> <body> <form runat="server"> <asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" /> </form> </body> </html>
Then add the script to build the list:
<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>
Then we add a subroutine that will be executed when the user clicks on an item in the RadioButtonList control. When the radio button is clicked, the text will appear in the 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>
- Previous Page WebForms Hashtable
- Next Page WebForms XML File