ASP.NET - Đối tượng Hashtable

Đối tượng Hashtable chứa các mục được biểu diễn bằng cặp khóa/giá trị.

Tạo Hashtable

Đối tượng Hashtable chứa các mục được biểu diễn bằng cặp khóa/giá trị. Khóa được sử dụng làm chỉ mục, thông qua việc tìm kiếm khóa, có thể thực hiện việc tìm kiếm giá trị nhanh chóng.

Thêm các mục vào Hashtable bằng phương thức Add().

Mã dưới đây tạo ra mộtHashtable có tên là mycountries và thêm bốn phần tử:

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

Gán dữ liệu

Đối tượng Hashtable có thể tự động tạo văn bản và giá trị cho các điều khiển sau:

  • asp:RadioButtonList
  • asp:CheckBoxList
  • asp:DropDownList
  • asp:Listbox

Nếu muốn gán dữ liệu vào một RadioButtonList, trước tiên hãy tạo một RadioButtonList trong một trang .aspx (không có các thẻ asp:ListItem)

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

Sau đó thêm vân bản xây dựng danh sách:

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

Sau đó chúng ta thêm một hàm con, hàm con này sẽ được thực thi khi người dùng nhấp vào một mục trong RadioButtonList. Khi một nút chọn đơn được nhấp, một dòng văn bản sẽ xuất hiện trong 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>

Hiển thị ví dụ này

Ghi chú:Bạn không thể chọn cách sắp xếp thứ tự các mục thêm vàoHashtable. Để sắp xếp các mục theo thứ tự字母 hoặc số, hãy sử dụng đối tượng SortedList.