ASP.NET - SortedList

SortedList มีคุณสมบัติของ ArrayList และ Hashtable

SortedList สามารถ

SortedList มีรายการที่แสดงด้วยคู่กุญแจ/ค่า SortedList สามารถจัดรายการโดยอัตโนมัติตามลำดับอักษรหรือลำดับเลข

เพิ่มรายการเข้า SortedList ด้วยวิธี Add(). SortedList สามารถปรับขนาดเรียบร้อยด้วยวิธี TrimToSize()

รหัสใต้นี้สร้าง SortedList ชื่อ mycountries และเพิ่มสี่อิเล็ม

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New SortedList
  mycountries.Add("C","China")
  mycountries.Add("S","Sweden")
  mycountries.Add("F","France")
  mycountries.Add("I","Italy")
end if
end sub
</script>

การเชื่อมโยงข้อมูล

SortedList สามารถสร้างข้อความและค่าสำหรับควบคุมด้านล่างโดยอัตโนมัติ

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

แสดงตัวอย่างนี้