ASP .NET - XML 文件
我們可以把 XML 文件綁定到列表控件。
實(shí)例
一個(gè) XML 文件
這里有一個(gè)名為 "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>
請(qǐng)查看該文件:countries.xml
把 DataSet 綁定到 List 控件
首先,導(dǎo)入 "System.Data" 命名空間。我們需要該命名空間與 DataSet 對(duì)象一起工作。把下面這條指令包含在 .aspx 頁(yè)面的頂部:
<%@ Import Namespace="System.Data" %>
接下來(lái),為這個(gè) XML 文件創(chuàng)建一個(gè) DataSet,并在頁(yè)面首先加載時(shí)把這個(gè) 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 控件,首先請(qǐng)?jiān)?.aspx 頁(yè)面中創(chuàng)建一個(gè) RadioButtonList 控件(沒(méi)有任何 asp:ListItem 元素):
<html>
<body>
<form runat="server">
<asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" />
</form>
</body>
</html>
然后添加構(gòu)建這個(gè) 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>
然后,我們添加一個(gè)子例程,該子例程會(huì)在用戶(hù)點(diǎn)擊 RadioButtonList 控件中的項(xiàng)目時(shí)執(zhí)行。當(dāng)用戶(hù)點(diǎn)擊某個(gè)單選按鈕時(shí),label 中會(huì)出現(xiàn)一條文本:
<%@ 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>