程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> 關於ASP.NET >> ASP.NET入門教程:Hashtable對象

ASP.NET入門教程:Hashtable對象

編輯:關於ASP.NET

上一節講述了ArrayList對象,下面開始講述Hashtable 對象包含用鍵/值對表示的項目。鍵被用作索引,通過搜索其鍵,可以實現對值的快速搜索。 

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

實例

例子 1 - Hashtable RadioButtonList

例子 2 - Hashtable RadiobuttonList

例子 3 - Hashtable DropDownList

創建 Hashtable

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

通過 Add() 方法向 Hashtable 添加項目。看到本信息,說明該文章來源於網頁教學網www.webjx.com,如果文章不完整請到網頁教學網webjx.com浏覽!

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

<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 元素)

<html>
<body>

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

</form>

</body>
</html>

然後添加構建列表的腳本:本信息代表文章來源網頁教學webjx.com請大家去www.webjx.com浏覽!

<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 中會出現一條文本:

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

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved