ASP.NET - Hashtable วัตถุ

วัตถุ Hashtable มีรายการที่แสดงด้วยคู่กุญแจ/ค่า

สร้าง Hashtable

วัตถุ Hashtable มีรายการที่แสดงด้วยคู่กุญแจ/ค่า กุญแจใช้เป็นดัชนี และสามารถค้นหาค่าอย่างรวดเร็วโดยการค้นหากุญแจ

เพิ่มรายการด้วยวิธี Add()

รหัสด้านล่างสร้าง Hashtable ชื่อ mycountries และเพิ่มสี่องค์ประกอบ

<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 โปรดสร้างควบคุม RadioButtonList ในหน้า .aspx (ไม่มี asp:ListItem ในไซต์)

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

หลังจากนั้นเพิ่มสคริปต์สำหรับการสร้างรายการ

<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 ควบคุม ควบคุมนั้นจะทำงานเมื่อมีการกดบนแถวหนึ่งของ Radio Button แล้ว 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