ASP.NET Web Forms - Hashtable Object


The Hashtable object contains items represented by key/value pairs.


Examples

Try it Yourself - Example

Hashtable RadiobuttonList 1

Hashtable RadiobuttonList 2

Hashtable DropDownList


Create Hashtable

The Hashtable object contains items represented by key/value pairs. The key is used as an index, and by searching the key, values can be found quickly.

Use the Add() method to add items to the Hashtable.

The following code creates a Hashtable object named mycountries and adds four elements:

<script runat="server">
Sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New Hashtable
mycountries.Add("N","Norway")
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 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 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 Hashtable
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 that is executed when the user clicks an item in the RadioButtonList control. When a radio button is clicked, a line of text appears in the label:

Example

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New Hashtable
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 Example »

Note:You cannot choose the sort order of items added to the Hashtable. To sort items alphabetically or numerically, use the SortedList object.


Other Extensions