ASP .NET - XML Files

« Previous Chapter Next Chapter »

We can bind an XML file to a list control.

An XML File

Here is an XML file named "players.xml":

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

<players>

<player>
  <text>Sachin</text>
  <value>N</value>
</player>

<player>
  <text>Pointing</text>
  <value>S</value>
</player>

<player>
  <text>Nadal</text>
  <value>F</value>
</player>

<player>
  <text>Saina</text>
  <value>I</value>
</player>

</players>

Bind a DataSet to a List Control

First, import the "System.Data" namespace. We need this namespace to work with DataSet objects. Include the following directive at the top of an .htmlx page:

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

Next, create a DataSet for the 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 players=New DataSet
  players.ReadXml(MapPath("players.xml"))
end if
end sub

To bind the DataSet to a RadioButtonList control, first create a RadioButtonList control (without any asp:ListItem elements) in an .htmlx page:

<html>
<body>

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

</body>
</html>

Then add the script that builds the XML DataSet:

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

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim players=New DataSet
  players.ReadXml(MapPath("players.xml"))
  rb.DataSource=players
  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 to be executed when the user clicks on an item in the RadioButtonList control. When a radio button is clicked, a text will appear in a label:

Example

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

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim players=New DataSet
  players.ReadXml(MapPath("players.xml"))
  rb.DataSource=players
  rb.DataValueField="value"
  rb.DataTextField="text"
  rb.DataBind()
end if
end sub

sub displayMessage(s as Object,e As EventArgs)
lbl1.text="Your favorite player 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 Chapter Next Chapter »

Have Any Suggestion? We Are Waiting To Hear from YOU!

Your Query was successfully sent!