Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

ASP.NET XML data binding


May 12, 2021 ASP.NET


Table of contents


ASP.NET Web Forms - XML file

In A SP.NET you can bind an XML file to a List control by using it as a data source. Please refer to this section.

We can bind XML files to list controls.


An XML file

Here's an XML file .xml":

<?xml version="1.0" encoding="ISO-8859-1"?>

<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>

Check out this XML file: .xml


Bind DataSet to the List control

First, import the System.Data namespace. W e need the namespace to work with the DataSet object. Include the following instruction at the top .aspx the page:

<%@ Import Namespace="System.Data" %>

Next, create a DataSet for the XML file and load the XML file into the DataSet the first time the page loads:

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New DataSet
mycountries.ReadXml(MapPath("countries.xml"))
end if
end sub

In order to bind data to the RadioButtonList control, first create a RadioButtonList control (without any asp:ListItem elements) in the .aspx page:

<html>
<body>

<form runat="server">
<asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" />
</form>

</body>
</html>

Then add the script that created XML DataSet and bind the values in XML DataSet to the RadioButtonList control:

<%@ 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 sub-routine that is executed when the user clicks on an item in the RadioButtonList control. When a single button is clicked, a line of text appears 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>

Demo Examples . . .

That's ASP.NET about XML data binding.

Related tutorials

XML tutorial