Latest web development tutorials

ASP.NET Hashtable

Hashtable 對象包含用鍵/值對錶示的項目。


Examples

嘗試一下- 實例

Hashtable RadiobuttonList 1

Hashtable RadiobuttonList 2

Hashtable DropDownList


創建Hashtable

Hashtable 對象包含用鍵/值對錶示的項目。 鍵被用作索引,通過搜索鍵,可以實現對值的快速搜索。

通過Add() 方法向Hashtable 添加項目。

下面的代碼創建了一個名為mycountries 的Hashtable 對象,並添加了四個元素:

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


數據綁定

Hashtable 對象可為下列的控件自動生成文本和值:

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

為了綁定數據到RadioButtonList 控件,首先要在.aspx 頁面中創建一個RadioButtonList 控件(不帶任何asp:ListItem 元素):

<html>
<body>

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

</body>
</html>

然後添加創建列表的腳本,並且綁定列表中的值到RadioButtonList 控件:

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

然後我們添加一個子例程,當用戶點擊RadioButtonList 控件中的某個項目時,該子例程會被執行。 當某個單選按鈕被點擊時,label 中會出現一行文本:

實例

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

演示實例»

註釋:您無法選擇添加到Hashtable的項目的排序方式。如需對項目進行字母排序或者數字排序,請使用SortedList 對象。