ASP.NET - XML file
- Previous Page WebForms SortedList
- Next Page WebForms Repeater
We can bind the XML file to the list control.
Example
An XML file
There is an XML file named "countries.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>
Please view this file:countries.xml
Bind the DataSet to the List control
First, import the "System.Data" namespace. We need this namespace to work with the DataSet object. Include the following directive at the top of the .aspx page:
<%@ Import Namespace="System.Data" %>
Next, create a DataSet for this XML file and load the XML file into the DataSet when the page is first loaded:
<script runat="server"> sub Page_Load if Not Page.IsPostBack then dim mycountries=New DataSet mycountries.ReadXml(MapPath("countries.xml")) end if end sub
If you need to bind the DataSet to the RadioButtonList control, first create a RadioButtonList control in the .aspx page (without any asp:ListItem elements):
<html> <body> <form runat="server"> <asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" /> </form> </body> </html>
Then add the script to build this 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>
Then, we add a subroutine that will be executed when the user clicks on an item in the RadioButtonList control. When the user clicks on a radio button, a text will appear in the label:
<%@ 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>
- Previous Page WebForms SortedList
- Next Page WebForms Repeater