How I can save a DatagridView in a Xml and Load A

2019-02-27 00:41发布

Hi I want to save and load data from a datagridview to a xml. My idea is that I can save my datagridview to a xml how this -> "[date]_[name].xml" and later I can load this data. For this two operations I want to use two methods --> Save() and Load()

Here is my code for saving:

private void Save(DataGridView grid) 
{
    try
    {
        xmlfile = @"C:\datagrid.xml";
        dataset = (DataSet)InputDataGrid.DataSource;
        dataset.WriteXml(xmlfile);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

How I can do this?

1条回答
forever°为你锁心
2楼-- · 2019-02-27 00:52

This is the sample xml file which I have used for testing your scenario:

<dataset>
  <student>
    <name>Tarasov</name>
  </student>
</dataset>

The sample code snippet which could access the above mentioned XML file:

private void Load()
{
    string path = @"C:\dataset.xml";
    DataSet ds = new DataSet();
    ds.ReadXml(path);
    InputDataGrid.DataSource = ds;
    InputDataGrid.DataMember = "student";
}

private void Save()
{
    string path = @"C:\dataset.xml";
    DataSet ds = (DataSet) InputDataGrid.DataSource;
    ds.WriteXml(path);
}

--SJ

查看更多
登录 后发表回答