Define a default name for the DataTable, and save the existing DataGreidView structure and data:
public const string DTBackUp = "DTBackUp";
dataGridView1.DataSource = dt;
WriteXML(dt);
When you want to restore the DataGridView:
DataTable dt = this.ReadXML();
this.dataGridView1.DataSource = dt;
Using these two methods:
private DataTable ReadXML()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "XML|*.xml";
DataSet dt = new DataSet();
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
dt.ReadXml(ofd.FileName);
return dt.Tables[0];
}
catch (Exception ex)
{
throw new DataException("Fail to read");
}
}
return null;
}
private void WriteXML(DataTable dt)
{
if (dt.TableName == "") dt.TableName = DTBackUp;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "XML|*.xml";
if (sfd.ShowDialog() == DialogResult.OK)
{
try
{
dt.WriteXml(sfd.FileName);
}
catch (Exception ex)
{
throw new DataException("Fail to write");
}
}
}