Latest web development tutorials

ASP.NET Hashtable

Hashtable object contains items with the key / value pairs expressed.


Examples

Try - Example

Hashtable RadiobuttonList 1

Hashtable RadiobuttonList 2

Hashtable DropDownList


Create Hashtable

Hashtable object contains items with the key / value pairs expressed. Key is used as the index by search key value can be achieved on a quick search.

Add items to Hashtable through Add () method.

The following code creates a Hashtable object called mycountries, and add the 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

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 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 to create the list, and the binding 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, when a user clicks on an item in the RadioButtonList control when the subroutine is executed. When a radio button is clicked, label will appear in the line of text:

Examples

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

The demonstration >>

Note: You can not choose to add to the Hashtable items are sorted.For the project alphabetical or numerical order, use the SortedList object.