ASP.NET - The Hashtable Object

« Previous Chapter Next Chapter »

The Hashtable object contains items in key/value pairs.

Create a Hashtable

The Hashtable object contains items in key/value pairs. The keys are used as indexes, and very quick searches can be made for values by searching through their keys.

Items are added to the Hashtable with the Add() method.

The Below code creates a Hashtable named players and four elements are added:

<script runat="server">
Sub Page_Load
if Not Page.IsPostBack then
  dim players=New Hashtable
  players.Add("N","Sachin")
  players.Add("S","Pointing")
  players.Add("F","Nadal")
  players.Add("I","Saina")
end if
end sub
</script>


Data Binding

A Hashtable object may automatically generate the text and values to the following controls:

  • asp:RadioButtonList
  • asp:CheckBoxList
  • asp:DropDownList
  • asp:Listbox

To bind data to a RadioButtonList control, first create a RadioButtonList control (without any asp:ListItem elements) in an .htmlx page:

<html>
<body>

<form runat="server">
<asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" />
</form>

</body>
</html>

Then add the script that builds the list:

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim players=New Hashtable
  players.Add("N","Sachin")
  players.Add("S","Pointing")
  players.Add("F","Nadal")
  players.Add("I","Saina")
  rb.DataSource=players
  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 sub routine to be executed when the user clicks on an item in the RadioButtonList control. When a radio button is clicked, a text will appear in a label:

Example

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim players=New Hashtable
  players.Add("N","Sachin")
  players.Add("S","Pointing")
  players.Add("F","Nadal")
  players.Add("I","Saina")
  rb.DataSource=players
  rb.DataValueField="Key"
  rb.DataTextField="Value"
  rb.DataBind()
end if
end sub

sub displayMessage(s as Object,e As EventArgs)
lbl1.text="Your favorite player 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 choose the sort order of the items added to the Hashtable. To sort items alphabetically or numerically, use the SortedList object.


« Previous Chapter Next Chapter »

Have Any Suggestion? We Are Waiting To Hear from YOU!

Your Query was successfully sent!