Runtime load XML File Data into Gridview Asp.Net C# VB.Net

In my previous article i have showed “How to load XML File Data into Gridview in Design View“. In this article or tutorial i will show you the same thing but using code. Due to necessity certain times we need to programically or dynamically display XML file data into Gridview. To do that open a project. Add a Gridview.

So HTML markup Would be (same for both C# and VB.Net):

    <asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5">

Add an XML File in your Project:
Right click on project. Select Add new Item. Then select XML File. The by default name is “XMLFile.xml”. No need to change the XML file name. The XML file automatically open in the code window. This process is same for both C# and VB.Net.

Now fill up the XML file with some data to test:

<?xml version="1.0" encoding="utf-8" ?>
  < Id="0001" Title="Bind Dropdown List" 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 write the below code under Page_Load event:
C# Code:

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

        //Read the contents of the XML file into the DataSet
        GridView1.DataSource = XMLDataSet.Tables[0].DefaultView;

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
        Dim XMLDataSet As DataSet
        Dim FilePath As String

        FilePath = Server.MapPath("XMLFile.xml")
        XMLDataSet = New DataSet()

        'Read the contents of the XML file into the DataSet
        GridView1.DataSource = XMLDataSet.Tables(0).DefaultView
    End Sub

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

Now run the project. Hope you will get the below desired output:

Download Code Example C#        Download Code Example VB.Net

Leave a Reply

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

AlphaOmega Captcha Classica  –  Enter Security Code