Latest web development tutorials

ASP.NET SortedList

SortedList objects combines the properties of an object and ArrayList Hashtable object.


Examples

Try - Example

SortedList RadiobuttonList 1

SortedList RadiobuttonList 2

SortedList DropDownList


SortedList objects

SortedList object contains items with the key / value pairs expressed. SortedList objects automatically sort the items in alphabetical order or numerical order.

By Add () method to add items to the SortedList. By TrimToSize () method to adjust the final size SortedList.

The following code creates a SortedList object called mycountries, and add the 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

SortedList object 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 an .aspx page (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 create the list, and the binding 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 subroutine, when a user clicks on an item in the RadioButtonList control when the subroutine is executed. When a radio button is clicked, label will appear in the line of text:

Examples

<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>

The demonstration >>