ASP.NET - Objek Hashtable

Objek Hashtable mengandung item yang diwakili oleh pasangan kunci/nilai.

Membuat Hashtable

Objek Hashtable mengandung item yang diwakili oleh pasangan kunci/nilai. Kunci digunakan sebagai indeks, melalui pencarian kunci, dapat melakukan pencarian nilai dengan cepat.

Menambahkan item ke Hashtable melalui metode Add().

Kode di bawah ini menciptakan satu Hashtable bernama mycountries dan menambahkan empat elemen:

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

Pengikat Data

Objek Hashtable dapat secara otomatis mengenerate teks dan nilai untuk kontrol berikut:

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

Untuk mengikat data ke kontrol RadioButtonList, pertama-tama buat kontrol RadioButtonList di halaman .aspx (tanpa elemen asp:ListItem)

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

Lalu tambahkan skrip untuk membangun daftar:

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

Lalu kami menambahkan satu sub-routine, yang akan dijalankan saat pengguna mengklik salah satu item di kontrol RadioButtonList. Saat tombol pilihan disentuh, label akan muncul teks:

<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 对象。