First of all, you'll never be good programmer, if you're trying to use the piece of code by copy-paste and without changing code on your own.
Second of all, your DataGridView control is bind to none DataSource, because you're adding rows directly!
private void add_Click(object sender, EventArgs e)
{
int n = dataGridView1.Rows.Add();
}
See:
Create an Unbound DataGridView Control - Windows Forms | Microsoft Docs[
^]
Third of all, your xml structure is wrong! Instead of:
<root>
<table>
<one>125</one>
<two>125</two>
<child>
<three>987</three>
</child>
</table>
</root>
it should be something like:
<root>
<table>
<row>
<one>125</one>
<two>128</two>
<child>
<three>987</three>
</child>
</row>
<row>
<one>321</one>
<two>216</two>
<child>
<three>999</three>
</child>
</row>
</table>
</root>
So, if you would like to export unbound data into xml file, you have to loop through the
collection of DataGridViewRows[
^].
private void Export_Click(object sender, EventArgs e)
{
const string FILENAME = @"c:\temp\test.xml";
XDocument doc = new XDocument(new XDeclaration("1.0", "ISO-8859-1", "yes"));
XElement root = new XElement("root");
XElement tbl = new XElement("table");
List<XElement> entries = DataGridView1.Rows.Cast<DataGridViewRow>()
.Select(row => new XElement("row", new XElement[]
{
new XElement("one", row.Cells[0].Value.ToString()),
new XElement("two", row.Cells[1].Value.ToString()),
new XElement("child", new XElement("three", row.Cells[2].Value.ToString()))
}))
.ToList();
tbl.Add(entries);
root.Add(tbl);
doc.Add(root);
doc.Save(FILENAME);
}
Good luck!