ASP.NET - SortedList オブジェクト

SortedList オブジェクトは ArrayList と Hashtable オブジェクトの特性を兼ね備えています。

SortedList オブジェクト

SortedList オブジェクトは、キー/値対で表される項目を含んでいます。SortedList オブジェクトは、文字順または数値順に自動的に項目をソートします。

Add() メソッドを使用して SortedList に項目を追加します。SortedList は TrimToSize() メソッドで最終サイズに調整できます。

以下のコードは、mycountries という名前の SortedList を作成し、4つの要素を追加します:

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

データバインディング

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>

次に、リストの構築スクリプトを追加します:

<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 コントロールの項目をクリックしたときに実行されるサブルーチンを追加します。ラジオボタンがクリックされたとき、テキストがラベルに表示されます:

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

この例を表示