ASP.NET - SortedList-objekt

SortedList-objektet har egenskaper från både ArrayList och Hashtable-objekt.

SortedList-objektet

SortedList-objektet innehåller poster representerade som nyckel/värde-par. SortedList-objektet kan automatiskt sortera poster i bokstavsordning eller numerisk ordning.

Lägg till objekt med Add() metod till SortedList. SortedList kan justeras till slutlig storlek med TrimToSize() metoden.

Följande kod skapar en namngiven mycountries SortedList och lägger till fyra element:

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

Databinding

SortedList-objektet kan automatiskt generera text och värden för följande kontroller:

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

För att binda data till RadioButtonList-kontrollen, skapa först ett RadioButtonList-kontroll i aspx-filen (ingen asp:ListItem-element):

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

Därefter lägg till skriptet för att bygga listan:

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

显示这个例子