当前位置:K88软件开发文章中心编程语言.NET.NET02 → 文章内容

ASP.NET Hashtable

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-14 1:44:50

ASP.NET Web Forms - Hashtable 对象Hashtable 对象包含用键/值对表示的项目。尝试一下 - 实例Hashtable RadiobuttonList 1Hashtable RadiobuttonList 2Hashtable DropDownList创建 HashtableHashtable 对象包含用键/值对表示的项目。键被用作索引,通过搜索键,可以实现对值的快速搜索。通过 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:RadioButtonListasp:CheckBoxListasp:DropDownListasp: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 对象。

ASP.NET Hashtable