Latest web development tutorials

ASP.NET SortedList

SortedList 對象結合了ArrayList 對象和Hashtable 對象的特性。


Examples

嘗試一下- 實例

SortedList RadiobuttonList 1

SortedList RadiobuttonList 2

SortedList DropDownList


SortedList 對象

SortedList 對象包含用鍵/值對錶示的項目。 SortedList 對象按照字母順序或者數字順序自動地對項目進行排序。

通過Add() 方法向SortedList 添加項目。 通過TrimToSize() 方法把SortedList 調整為最終尺寸。

下面的代碼創建了一個名為mycountries 的SortedList 對象,並添加了四個元素:

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New SortedList
mycountries.Add("N","Norway")
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 控件,首先要在.aspx 頁面中創建一個RadioButtonList 控件(不帶任何asp:ListItem 元素):

<html>
<body>

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

</body>
</html>

然後添加創建列表的腳本,並且綁定列表中的值到RadioButtonList 控件:

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New SortedList
mycountries.Add("N","Norway")
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("N","Norway")
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>

演示實例»