How to Bind XML File Data into a ListBox Control ASP.NET C# VB.Net

In my previous examples I have described How to Bind Database data, DataTable Data, SP Data into a ListBox Control.But I think one another DataSource is also an essential which is XML DataSource. So in this article I will explain How you can Bind a ListBox Control with XML Data.

Output to Achieve:
How to Bind XML File Data to ListBox Control ASP.NET Csharp VB.Net

To do the Example First Add an XML File Like Below:

<?xml version="1.0" encoding="utf-8" ?>
  < Id="0001" Title="Bind ListBox" Visit="985" Modified="Jan 01, 2009">
  < Id="0002" Title="Event calendar" Visit="777" Modified="Feb 01, 2009">
  < Id="0003" Title="Select all checkboxes" Visit="853" Modified="Mar 01, 2009">
  < Id="0004" Title="Transfer data between" Visit="957" Modified="Apr 01, 2009">

Now Add a ListBox to Bind:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>

Now Bind the XML file with the ListBox Control:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            DataSet XMLDataSet;
            string FilePath = Server.MapPath("XMLFile.xml");
            XMLDataSet = new DataSet();

            //Read the contents of the XML file into the DataSet
            ListBox1.DataSource = XMLDataSet.Tables[0].DefaultView;
            ListBox1.DataValueField = "ID";
            ListBox1.DataTextField = "Title";

Note: Don’t forget to add “using System.Data;” namespace.

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim XMLDataSet As DataSet
            Dim FilePath As String = Server.MapPath("XMLFile.xml")
            XMLDataSet = New DataSet()

            'Read the contents of the XML file into the DataSet
            ListBox1.DataSource = XMLDataSet.Tables(0).DefaultView
            ListBox1.DataValueField = "ID"
            ListBox1.DataTextField = "Title"
        End If
    End Sub

Hope now you can Bind XML DataSource into a ListBox Control.

Download Code Example C#        Download Code Example VB.Net

Posted in .Net,, C#, ListBox, VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *