ASP.NET Web Forms
- SortedList object
ASP.NET SortedList object represents a collection of key/value pairs that sort keys and can be accessed by key and index.
The SortedList object combines the properties of the ArrayList object with the Hashtable object.
Try it - instance
SortedList RadiobuttonList 1
SortedList RadiobuttonList 2
SortedList DropDownList
SortedList object
The SortedList object contains items represented by key/value pairs.
SortedList objects automatically sort items in alphabetical or numerical order.
Add an item to SortedList using the Add() method.
The SortedList is adjusted to the final size by the TrimToSize() method.
The following code creates a SortedList object called mycountries and adds four elements:
<script runat="server">
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
The SortedList object automatically generates text and values for the following controls:
-
asp:RadioButtonList
-
asp:CheckBoxList
-
asp:DropDownList
-
asp:Listbox
In order to bind data to the RadioButtonList control, first create a RadioButtonList control (without any asp:ListItem elements) in the .aspx page:
<html>
<body>
<form runat="server">
<asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" />
</form>
</body>
</html>
Then add the script that created the list, and bind the values in the list to the RadioButtonList control:
<script runat="server">
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 sub-routine that is executed when the user clicks on an item in the RadioButtonList control.
When a single button is clicked, a line of text appears in the label:
<script runat="server">
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>
Demo Examples . . .
That's ASP.NET use of the SortedList object.