Saturday 2 June 2012

Show Data in GridView taking from Xml


Introduction:

In this article we will discuss how we can show the data into DataGridView from XML file. now we create an XML file. 

Create an XML file:

<?xml version="1.0" encoding="utf-8" ?>
    <bookstore>
    <book>
        <title> The </title>
        <price> 8.99 </price>
        <genre> autobiograph </genre>
        <publicationdate> 1981 </publicationdate>
        <ISBN> 1-861003-11- </ISBN>
    </book>

    <book>
        <title> The Confiden </title>
        <price> 11.99 </price>
        <genre> novel </genre>
        <publicationdate> 1967 </publicationdate>
        <ISBN> 0-201-63361- </ISBN>
    </book>

    <book>
        <title> The Gorgias </title>
        <price> 9.99 </price>
        <genre> philosophy </genre>
        <publicationdate> 1991 </publicationdate>
        <ISBN> ss1-861001-57- </ISBN>
    </book>
</bookstore>
   
Create the window application: There are the following steps for creating the window application.

Step 1: Create new project.

Step 2: Drag DataGridView control from the toolbox and drop on the form, and set the properties of the DataGridView contol.

Step 3: Add the following namespace:

using System.Data.SqlClient;
using System.Xml;

Step 4: Write the code on the form load event.

For Example:

Form1.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Xml;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            XmlDataDocument xmlDatadoc = new XmlDataDocument();
            xmlDatadoc.DataSet.ReadXml("C:\\books.xml");
            DataSet ds = new DataSet("Books DataSet");
            ds = xmlDatadoc.DataSet;
            dataGridView1.DataSource = ds.DefaultViewManager;
            dataGridView1.DataMember = "Book";
        }
    }
}

Step 5: Build and debug the application. You will see the following output:



Figure 1: Data in to DataGridView

To view the demo of this application:

Download zip folder --> right click on that folder --> Click on extract all.

Now copy that folder and paste in to virtual directory.

You will get an XML file in that folder --> Copy that file and paste in to C drive because in the application we have to pass the path as follows:

xmlDatadoc.DataSet.ReadXml("C:\\books.xml");

At last open the Microsoft visual studio 2005 and open the project.

No comments:

Post a Comment