ASP.NET - XMLファイル
- 前のページ WebForms SortedList
- 次のページ WebForms Repeater
XMLファイルをリストコントロールにバインドすることができます。
XMLファイル
「countries.xml」と呼ばれるXMLファイルがあります:
<?xml version="1.0" encoding="ISO-8859-1"?> <countries> <country> <text>China</text> <value>C</value> </country> <country> <text>Sweden</text> <value>S</value> </country> <country> <text>France</text> <value>F</value> </country> <country> <text>Italy</text> <value>I</value> </country> </countries>
このファイルを確認してください:countries.xml
DataSetをListコントロールにバインドする
まず「System.Data」ネームスペースをインポートします。DataSetオブジェクトと一緒に使用するために必要です。以下のインストラクションを.aspxページの先頭に含めます:
<%@ Import Namespace="System.Data" %>
次に、このXMLファイルに対してDataSetを作成し、ページが最初に読み込まれた際にXMLファイルをDataSetに読み込んでください:
<script runat="server"> sub Page_Load if Not Page.IsPostBack then dim mycountries=New DataSet mycountries.ReadXml(MapPath("countries.xml")) end if end sub
このDataSetをRadioButtonListコントロールにバインドするには、まず.aspxページでRadioButtonListコントロールを作成してください(asp:ListItem要素は含まないでください):
<html> <body> <form runat="server"> <asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" /> </form> </body> </html>
次に、この XML DataSet を構築するスクリプトを追加します:
<%@ Import Namespace="System.Data" %> <script runat="server"> sub Page_Load if Not Page.IsPostBack then dim mycountries=New DataSet mycountries.ReadXml(MapPath("countries.xml")) rb.DataSource=mycountries rb.DataValueField="value" rb.DataTextField="text" rb.DataBind() end if end sub </script> <html> <body> <form runat="server"> <asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" onSelectedIndexChanged="displayMessage" /> </form> </body> </html>
その後、ユーザーが RadioButtonList コントロールのアイテムをクリックしたときに実行されるサブルーチンを追加します。ユーザーがどのオプションを選択したかによらず、ラベルにテキストが表示されます:
<%@ Import Namespace="System.Data" %> <script runat="server"> sub Page_Load if Not Page.IsPostBack then dim mycountries=New DataSet mycountries.ReadXml(MapPath("countries.xml")) rb.DataSource=mycountries rb.DataValueField="value" rb.DataTextField="text" 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>
- 前のページ WebForms SortedList
- 次のページ WebForms Repeater