Web Pages Tutor...login
Web Pages Tutorial
author:php.cn  update time:2022-04-11 14:20:28

Web Forms SortedList



SortedList object combines the characteristics of ArrayList object and Hashtable object.


Try it - Example

SortedList RadiobuttonList 1

SortedList RadiobuttonList 2

SortedList DropDownList


SortedList Object

SortedList object contains items represented by key/value pairs. A SortedList object automatically sorts items in alphabetical or numerical order.

Add items to SortedList through the Add() method. Adjust the SortedList to its final size through the TrimToSize() method.

The following code creates a SortedList object named 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 can automatically generate 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 in the .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 that creates 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 subexample This subroutine will be executed when the user clicks an item in the RadioButtonList control. When a radio button is clicked, a line of text will appear in the label:

Instance

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

<!DOCTYPE html>
<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>

Run Example»

Click the "Run Instance" button to view the online instance


php.cn