ASP.NET Web Forms – SortedList 物件簡介

大雄45發表於2022-04-26
導讀 SortedList 物件結合了 ArrayList 物件和 Hashtable 物件的特性。

ASP.NET Web Forms – SortedList 物件簡介ASP.NET Web Forms – 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 可以後續的控制元件自動生成文字和值:

  1. asp:單選按鈕列表
  2. asp:核取方塊列表
  3. asp:下拉選單
  4. asp:列表框

為了將資料繫結到 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 時,會在該控制元件中新增一個程式的專案時,執行。當單選按鈕被點選時,中會行的標籤文字:

例項

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

原文來自: l


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69955379/viewspace-2888764/,如需轉載,請註明出處,否則將追究法律責任。

相關文章