How to Read data from XML File and Bind to Gridview in with C# - Example

In previous article we have learned How to Import Data From Excel file to Database in with C# - Example. an you can find other Gridview example here Gridview Here in this post we will discuss how to Read Data from XML file and bind it to grid view. It is very simple task you just have to create one DataSet object and call the method ReadXml() you have to pass one argument in it, which is file name from which you want to read data.

first of all i have one xml file Contact.xml it is as per following.

<?xml version="1.0" encoding="utf-8" ?>
    <Name>steve jobs</Name>
    <Name>Bill gates</Name>
    <Name>Peter Capaldi</Name>

Here is the screen shot of my grid which is binded from XML file

Source Code in

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="XMLtoGrid.aspx.cs" Inherits="BlogCodeTester.XMLtoGrid" %>

<!DOCTYPE html>

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
            <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                <EditRowStyle BackColor="#999999" />
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#41B7D8" Font-Bold="True" ForeColor="White" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />


Code in C#:-

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BlogCodeTester
    public partial class XMLtoGrid : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
        private void readFromXML()
            string myfile = @Server.MapPath("~/Contact.xml");
            DataSet ds = new DataSet();
            if (ds.Tables[0].Rows.Count > 0)
                GridView1.DataSource = ds;
                Response.Write("No data to display");

Post a Comment