Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,How to save a DataGridView in to a xmlfile with same header's column in DataGridView?
for example, my header's column in DataGridView are:c1,c2,c3,c4
and my xmlfile must be following structure,How can I create it?

XML
<Dataset>
  <r>
    <C1>v1</C1>
    <C2>v2</C2>
    <C3>v3</C3>
    <C4>v4</C4>
  </r>
  <r>
    <C1>t1</C1>
    <C2>t2</C2>
    <C3>t3</C3>
    <C4>t4</C4>
  </r>
</DataSet>
Posted
Comments
DamithSL 16-Aug-15 1:59am    
update the question with your code
Maciej Los 16-Aug-15 5:42am    
What's datagridview datasource? What have you tried? Where are you stuck?
Sergey Alexandrovich Kryukov 16-Aug-15 9:46am    
Your biggest mistake is using the different column tags, C1, C2...
—SA

1 solution

There's few options. One of them is to use XmlDocument[^] and XmlElement[^] class.

C#
XmlDocument xdoc = new XmlDocument();
XmlElement xroot = new XmlElement("DataSet");
XmlElement xele;

foreach(DataGridViewRow dgr in DataGridView1.Rows)
{
    xele = new XmlElement("r");
    foreach(DataGridViewColumn dgc in DataGridView1.Columns)
    {
        xele.Add(new XmlElement(dgc.Name, dgr.Cells[dgc.Index].Value);
    }
    xroot.Add(xele);
}
xdoc.Add(xroot);


For further information, please see:
DataGridViewRow[^]
DataGridView.Rows[^]
DataGridViewColumn[^]
DataGridView.Columns[^]
 
Share this answer
 
Comments
Wendelius 16-Aug-15 6:49am    
Looks good, 5.
Maciej Los 16-Aug-15 16:42pm    
Thank you, Mika.
Member 11276287 17-Aug-15 23:57pm    
Thank you, Maciej Los.The following code works but adds a extra empty row(empty nodes in xmldoc);

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.AppendChild(declare1);
XmlElement root = xmlDoc.CreateElement("Dataset");
xmlDoc.AppendChild(root);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
XmlNode xr = xmlDoc.CreateElement("r");
root.AppendChild(xr);
foreach (DataGridViewCell cell in row.Cells)
{
XmlNode node = xmlDoc.CreateElement(dataGridView1.Columns[cell.ColumnIndex].Name);
if (cell.Value != null)
node.InnerText = cell.Value.ToString();
xr.AppendChild(node);
}
}


/////////Why an empty row is added?
Maciej Los 18-Aug-15 1:57am    
My code does not add empty nodes, unless you have hidden, empty rows in DataGridView...
Member 11276287 18-Aug-15 3:46am    
I don't have hidden rows in DataGridView but after entering data,an empty row added auto....
also with running your code, program has error in all uses add-method and code:
new XmlElement("DataSet");

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900