ASP.NET Web Forms - Hashtable object
This section describes the process of using the ASP.NETHashtable object to bind data.
A Hashtable object contains items represented by key/value pairs.
Hashtable RadiobuttonList 1
Hashtable RadiobuttonList 2
Hashtable DropDownList
A Hashtable object contains items represented by key/value pairs. The key is used as an index, and by searching for the key, a quick search of the value can be achieved.
Add items to the Hashtable through the Add() method.
The following code creates a Hashtable object named mycountries and adds four elements:
<script runat="server">Sub Page_Loadif Not Page.IsPostBack thendim mycountries=New Hashtablemycountries.Add("N","Norway")mycountries.Add("S","Sweden")mycountries.Add("F", "France")mycountries.Add("I","Italy")end ifend sub</script>
Hashtable objects 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 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 that creates the list and bind the values in the list to the RadioButtonList control:
<script runat="server">sub Page_Loadif Not Page.IsPostBack thendim mycountries=New Hashtablemycountries.Add("N","Norway")mycountries.Add("S","Sweden")mycountries.Add("F","France")mycountries.Add("I","Italy")rb. DataSource=mycountriesrb.DataValueField="Key"rb.DataTextField="Value"rb.DataBind()end ifend 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 will appear in the label:
<script runat="server">sub Page_Loadif Not Page.IsPostBack thendim mycountries=New Hashtablemycountries.Add("N","Norway")mycountries.Add("S","Sweden")mycountries.Add("F","France")mycountries.Add("I","Italy")rb. DataSource=mycountriesrb.DataValueField="Key"rb.DataTextField="Value"rb.DataBind()end ifend subsub displayMessage(s as Object,e As EventArgs)lbl1.text="Your favorite country is: " & rb.SelectedItem.Textend 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>
Note: You cannot choose how items added to a Hashtable are sorted. To sort items alphabetically or numerically, use a SortedList object.