建立 Hashtable
Hashtable 對象包含用鍵/值對錶示的項目。鍵被用作索引,通過搜尋其鍵,可以實現對值的快速搜尋。
通過 Add() 方法向 Hashtable 添加項目。
下面的代碼建立一個名為 mycountries 的 Hashtable,並添加了四個元素:
Code
<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>
資料繫結
Hashtable 對象可為下面這些控制項自動地產生文本和值:
- asp:RadioButtonList
- asp:CheckBoxList
- asp:DropDownList
- asp:Listbox
如需把資料繫結到某個 RadioButtonList 控制項,首先請在一個 .aspx 頁面中建立 RadioButtonList 控制項(沒有任何 asp:ListItem 元素)
Code
<html>
<body>
<form runat="server">
<asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" />
</form>
</body>
</html>
然後添加構建列表的指令碼:
Code
<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>
然後我們添加一個子常式,該常式會在使用者點擊 RadioButtonList 控制項中的某個項目時被執行。當某個選項按鈕被點擊,label 中會出現一條文本
Code
<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>