ASP.NET - Hashtableオブジェクト

Hashtableオブジェクトはキー/値対で表現された項目を含んでいます。

Hashtableの作成

Hashtableオブジェクトはキー/値対で表現された項目を含んでいます。キーはインデックスとして使用され、キーを検索することで値を迅速に検索できます。

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

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

<script runat="server">
Sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New Hashtable
  mycountries.Add("C","China")
  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>

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

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New Hashtable
  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 Hashtable
  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="あなたの好きな国は: " & 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 オブジェクトを使用してください。