Load XML File Into a DataGridView Using C#

How to Load an XML File into a DataGridView

 
In ADO.NET, the DataSet class implements methods and properties to work with XML documents, including reading XML, loading it into a DataSet and writing a DataSet back to an XML file. 
 
The ReadXml method reads an XML file and loads it into a DataSet. ReadXml is an overloaded method; you can use it to read a data stream, TextReader, XmlReader, or an XML file and store the data into a DataSet object, that can later be used to display the data in a tabular format. 
 
The following code snippet loads a Books.xml file into a DataSet. Here the file C:\Books\Books.xml" is the XML file that you want to display in a DataGridView control. 
  1. DataSet dataSet = new DataSet();  
  2. dataSet.ReadXml(@"C:\Books\Books.xml");  
The following code snippet binds the default DataTable with a DataGridView control. 
  1. dataGridView1.DataSource = dataSet.Tables[0];  
NOTE:  Make sure you add a reference to the System.Data namespace before using DataSet in your code.
 
Sample
  • Download the attached file and copy it to your local machine in some folder and change the full path of the XML file passed in the ReadXml method. 
  • Create a Windows Forms application.
  • Add a DataGridView Control to the Form.
  • Add a Button control, double-click on it and add the following code to the button click event handler. 
  1. DataSet dataSet = new DataSet();  
  2. dataSet.ReadXml(@"C:\Books\Books.xml");  
  3. dataGridView1.DataSource = dataSet.Tables[0];  
The output will be a DataGridView displaying the contents of an XML file. 
 
LoadXmlInDataSet.png


Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.