ASP.NET Web Forms - Hashtable 對象
本節描述使用ASP.NETHashtable 物件來綁定資料的過程。
Hashtable 物件包含以鍵/值對錶示的項目。
Hashtable RadiobuttonList 1
Hashtable RadiobuttonList 2
Hashtable DropDownList
Hashtable 物件包含以鍵/值對錶示的項目。鍵被用作索引,透過搜尋鍵,可以實現對值的快速搜尋。
透過Add() 方法為Hashtable 新增項目。
下面的程式碼建立了一個名為mycountries 的Hashtable 對象,並加入了四個元素:
<script runat="server">Sub Page_Loadif Not Page.IsPostBack thendim mycountries=New Hashtablemycountries.Add("N","Norway")mycountries.Add("S","Sweden")mycountries.Add("F", "France")mycountries.Add("I","Italy")end ifend 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_Loadif Not Page.IsPostBack thendim mycountries=New Hashtablemycountries.Add("N","Norway")mycountries.Add("S","Sweden")mycountries.Add("F","France")mycountries.Add("I","Italy")rb. DataSource=mycountriesrb.DataValueField="Key"rb.DataTextField="Value"rb.DataBind()end ifend 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_Loadif Not Page.IsPostBack thendim mycountries=New Hashtablemycountries.Add("N","Norway")mycountries.Add("S","Sweden")mycountries.Add("F","France")mycountries.Add("I","Italy")rb. DataSource=mycountriesrb.DataValueField="Key"rb.DataTextField="Value"rb.DataBind()end ifend subsub displayMessage(s as Object,e As EventArgs)lbl1.text="Your favorite country is: " & rb.SelectedItem.Textend 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 物件。