ASP.NET - ArrayListオブジェクト
- 前のページ WebForms データバインディング
- 次のページ WebForms Hashtable
ArrayListオブジェクトは単一のデータ値を含むプロジェクトの集合です。
ArrayListの作成
ArrayListオブジェクトは単一のデータ値を含むプロジェクトの集合です。
Add()メソッドを使用してArrayListにプロジェクトを追加します。
以下のコードは新しいArrayListオブジェクトmycountriesを作成し、4つのプロジェクトを追加します:
<script runat="server"> Sub Page_Load if Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("China") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") 終了 if 終了 sub </script>
デフォルトでは、ArrayListオブジェクトには16個のエントリが含まれています。TrimToSize()メソッドを使用してArrayListを最終サイズに調整できます:
<script runat="server"> Sub Page_Load if Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("China") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") mycountries.TrimToSize() 終了 if 終了 sub </script>
Sort()メソッドを通じて、ArrayListはアルファベット順または数字順にソートすることもできます:
<script runat="server"> Sub Page_Load if Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("China") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") mycountries.TrimToSize() mycountries.Sort() 終了 if 終了 sub </script>
逆順のソートを実現するには、Sort()メソッドの後にReverse()メソッドを適用してください:
<script runat="server"> Sub Page_Load if Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("China") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") mycountries.TrimToSize() mycountries.Sort() mycountries.Reverse() 終了 if 終了 sub </script>
データをArrayListにバインドする
ArrayListオブジェクトは以下のこれらのコントロールにテキストと値を自動生成できます:
- asp:RadioButtonList
- asp:CheckBoxList
- asp:DropDownList
- asp:Listbox
データをRadioButtonListコントロールにバインドするには、まず.aspxページでRadioButtonListコントロールを作成してください(asp:ListItem要素は一切ありませんのでご注意ください)
<html> <body> <form runat="server"> <asp:RadioButtonList id="rb" runat="server" /> </form> </body> </html>
次にリストを構築するスクリプトを追加し、リストの値をRadioButtonListコントロールにバインドします:
<script runat="server"> Sub Page_Load if Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("China") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") mycountries.TrimToSize() mycountries.Sort() rb.DataSource=mycountries rb.DataBind() 終了 if 終了 sub </script> <html> <body> <form runat="server"> <asp:RadioButtonList id="rb" runat="server" /> </form> </body> </html>
RadioButtonListコントロールのDataSource属性がこのArrayListに設定され、RadioButtonListコントロールのデータソースを定義しています。RadioButtonListコントロールの.DataBind()メソッドはRadioButtonListコントロールとデータソースをバインドします。
注記:データ値はコントロールの TextおよびValue属性として使用されます。Textとは異なるValueを追加する場合は、HashtableオブジェクトまたはSortedListオブジェクトを使用できます。
- 前のページ WebForms データバインディング
- 次のページ WebForms Hashtable