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

Đối tượng SortedList có tính chất của cả ArrayList và Hashtable.

Đối tượng SortedList

Đối tượng SortedList chứa các mục được biểu thị bằng cặp khóa/giá trị. Đối tượng SortedList có thể tự động sắp xếp các mục theo thứ tự 字符 hoặc số.

Thêm các mục vào SortedList bằng phương thức Add(). SortedList có thể điều chỉnh kích thước cuối cùng bằng phương thức TrimToSize().

Mã dưới đây tạo ra một SortedList 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 SortedList
  mycountries.Add("C","China")
  mycountries.Add("S","Sweden")
  mycountries.Add("F","France")
  mycountries.Add("I","Italy")
end if
end sub
</script>

Liên kết dữ liệu

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

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

Nếu muốn liên kết dữ liệu vào điều khiển RadioButtonList, trước tiên hãy tạo một điều khiển RadioButtonList trong tệp aspx (không có bất kỳ thẻ asp:ListItem nào):

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

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

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

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ục trong điều khiển RadioButtonList. Khi nút chọn được nhấp, 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 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>

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