Hashtable 对象包含用键/值对表示的项目。
创建哈希表
Hashtable包含用键对表示的项目。键被快速索引,通过搜索键,可以实现对值的搜索。
通过 Add() 方法向 Hashtable 添加项目。
下面的代码创建了一个名为 mycountries 的 Hashtable 对象,并添加了四个元素:
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
数据绑定
Hashtable 可以后续的控件自动生成文本和值:
- asp:单选按钮列表
- asp:复选框列表
- asp:下拉列表
- asp:列表框
为了将数据绑定到 RadioButtonList 控件,首先要在 .aspx 页面中创建一个 RadioButtonList 控件(不带 asp:ListItem 元素):
然后添加创建列表的脚本,然后将绑定列表中的值添加到 RadioButtonList 控件中:
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
然后我们示例,当用户点击该控件中的 RadioButtonList 时,会在该控件中添加一个程序的项目时,执行。当单选按钮被点击时,中会行的标签文本:
实例
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
注释:您无法选择添加到 Hashtable 的项目的示例方式。如需对项目进行示例或数字示例,请使用 SortedList。