ASP.NET Web Forms - Hashtable オブジェクト


Hashtable オブジェクトには、キー/値ペアで表される項目が含まれます。


Examples

試してみる - サンプル

Hashtable RadiobuttonList 1

Hashtable RadiobuttonList 2

Hashtable DropDownList


Hashtable の作成

Hashtable オブジェクトには、キー/値ペアで表される項目が含まれます。キーはインデックスとして使用され、キーを検索することで、値への高速検索を実現できます。

Add() メソッドを使用して Hashtable に項目を追加します。

次のコードは、mycountries という名前の Hashtable オブジェクトを作成し、4つの要素を追加します:

<script runat="server">
Sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New Hashtable
mycountries.Add("N","Norway")
mycountries.Add("S","Sweden")
mycountries.Add("F","France")
mycountries.Add("I","Italy")
end if
end sub
</script>


データバインディング

Hashtable オブジェクトは、次のコントロールのテキストと値を自動的に生成できます:

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

デモサンプル »

注記:Hashtable に追加された項目の並べ替え方法を選択することはできません。項目をアルファベット順または数字順に並べ替える必要がある場合は、SortedList オブジェクトを使用してください。


その他の拡張