How to write xml from datagridview in C#

Suppose if you need to generate the XML file from the datagridview data, simply you can use the dataset.WriteXML() function for writing the XML from the dataset object.

And now if I created one dataGridView1 in a Form to which I added some rows and columns without using any binding source or datasource properties and Now I need to send the data of dataGridView1 to an XML file, then you can create a dataset from the rows of the datagridview control.

 DataTable dt = new DataTable();
 for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
 {
  DataColumn column = new DataColumn(dataGridView1.Columns[i - 1].HeaderText);
  dt.Add(column);
  }
 int ColumnCount = dataGridView1.Columns.Count;
 foreach (GridViewRow dr in dataGridView1.Rows)
   {
    DataRow dataRow = dt.NewRow();
    for (int i = 0; i < ColumnCount; i++)
      {
         dataRow[i] = dr.Cells[i].Text;
      }
    }
 
  DataSet ds = new DataSet();
  ds.Tables.Add(dt);
  XmlTextWriter newXml = new XmlTextWriter("d:/newXML.xml", Encoding.UTF8);
  ds.WriteXml(newXml);

 
And another case if Datagridview have the datasource means you are binding the datagridview with the datasource then you can use following code of lines:
 

Dataset ds= datagridview1.datasource;
XmlTextWriter newXml = new XmlTextWriter("d:/newXML.xml", Encoding.UTF8);
ds.WriteXml(newXml);

3 thoughts on “How to write xml from datagridview in C#”

Comments are closed.