ASP.NET - Hashtable Object
- Previous Page WebForms ArrayList
- Next Page WebForms SortedList
The Hashtable object contains items represented by key/value pairs.
Create Hashtable
The Hashtable object contains items represented by key/value pairs. The key is used as an index, and by searching its key, a quick search of the value can be achieved.
Items are added to the Hashtable using the Add() method.
The following code creates a Hashtable named mycountries and adds four elements to it:
<script runat="server"> Sub Page_Load if Not Page.IsPostBack then dim mycountries=New Hashtable mycountries.Add("C","China") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") end if end sub </script>
Data Binding
The Hashtable 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 a .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 build the list:
<script runat="server"> sub Page_Load if Not Page.IsPostBack then dim mycountries=New Hashtable mycountries.Add("C","China") 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 on an item in the RadioButtonList control. When a radio button is clicked, a text will appear in the label:
<script runat="server"> sub Page_Load if Not Page.IsPostBack then dim mycountries=New Hashtable mycountries.Add("C","China") 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>
Note:You cannot select the sorting method for adding items to the Hashtable. To sort items alphabetically or numerically, please use the SortedList object.
- Previous Page WebForms ArrayList
- Next Page WebForms SortedList