ASP.NET - Obiekt SortedList

Obiekt SortedList łączy cechy obiektów ArrayList i Hashtable.Obiekt SortedList automatycznie sortuje elementy według kolejności liter lub liczbowej.

Obiekt SortedList

Obiekt SortedList zawiera elementy reprezentowane za pomocą par klucz/wartość. Obiekt SortedList automatycznie sortuje elementy według kolejności liter lub liczbowej.

Dodaj elementy do SortedList za pomocą metody Add(). SortedList można dostosować do ostatecznego rozmiaru za pomocą metody TrimToSize().

Poniższy kod tworzy obiekt SortedList o nazwie mycountries i dodaje cztery elementy:

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

Dawanie danych

Obiekt SortedList automatycznie generuje tekst i wartości dla poniższych kontrolki:

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

Aby przypisać dane do kontrolki RadioButtonList, najpierw utwórz kontrolkę RadioButtonList w pliku aspx (bez żadnych elementów asp:ListItem):

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

Następnie dodaj skrypt do tworzenia listy:

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

Następnie dodajemy procedurę podprogramową, która będzie wykonywana, gdy użytkownik kliknie na element w kontrolce RadioButtonList. Kiedy jest kliknięty przycisk radiowy, tekst pojawi się w etykiecie: }}

<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="Twoja ulubiona kraj to: " & 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>

Wyświetl ten przykład