ASP.NET Web Forms - XML File
We can bind an XML file to list controls.
An XML File
Here is an XML file named "countries.xml":
<countries>
<country>
<text>Norway</text>
<value>N</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>
View this XML file:countries.xml
Bind DataSet to List Controls
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:
Next, create a DataSet for the XML file, and load the XML file into the DataSet when the page is first loaded:
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New DataSet
mycountries.ReadXml(MapPath("countries.xml"))
end if
end sub
To bind data to the RadioButtonList control, first create a RadioButtonList control in the .aspx page (without any asp:ListItem elements):
<body>
<form runat="server">
<asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" />
</form>
</body>
</html>
Then add the script that creates the XML DataSet and binds the values in the XML DataSet to the RadioButtonList control:
<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 an item in the RadioButtonList control. When a radio button is clicked, a line of text will appear in the label:
Example
<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>
Demo »
Other Extensions