ASP.NET Web Forms - SortedList Object
The SortedList object combines the features of the ArrayList object and the Hashtable object.
Try it - Example
SortedList RadiobuttonList 1
SortedList RadiobuttonList 2
SortedList DropDownList
SortedList Object
A SortedList object contains items represented by key/value pairs. The SortedList object automatically sorts items in alphabetical or numerical order.
Add items to a SortedList using the Add() method. Use the TrimToSize() method to resize the SortedList to its final size.
The following code creates a SortedList object named mycountries and adds four elements:
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New SortedList
mycountries.Add("N","Norway")
mycountries.Add("S","Sweden")
mycountries.Add("F","France")
mycountries.Add("I","Italy")
end if
end sub
</script>
Data Binding
SortedList objects can automatically generate text and values for the following controls:
- asp:RadioButtonList
- asp:CheckBoxList
- asp:DropDownList
- asp:Listbox
To bind data to a RadioButtonList control, first create a RadioButtonList control in the .aspx page (without any asp:ListItem elements):
<body>
<form runat="server">
<asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" />
</form>
</body>
</html>
Then add a script that creates the list, and bind the values in the list to the RadioButtonList control:
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New SortedList
mycountries.Add("N","Norway")
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 an item in the RadioButtonList control. When a radio button is clicked, a line of text appears in the label:
Example
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New SortedList
mycountries.Add("N","Norway")
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>
Show example »
Other extensions