将已编辑的DataGridView保存到Datatable

时间:2016-02-28 08:38:10

标签: c# datagridview datatable

我是DataGridView的新用户 我想创建一个简单的应用程序,将XML读取到dataGridview编辑它而不是将其保存回XML 我的问题是保存到DataSet / DataTable 这是我的代码:

    //I want to change column name than save it to file
    var column = DG_dataGridView.Columns[ColumnIndex];

    column.Name = ColumnName;
    column.HeaderText = ColumnName;

    string dataFile = "c:\test.xml"
    DataTable dataTable = (DataTable)DG_dataGridView.DataSource;

    dataTable.DataSet.WriteXml(dataFile);

当我查看dataTable对象时,虽然我看到GUIdataGridView对象中的更改

,但我发现没有设置任何更改

1 个答案:

答案 0 :(得分:0)

请记住,您正在GridView中进行更改,而不是DataSource。您必须遍历GridView并生成新的DataTable

创建一个单独的函数:

private void WriteToFile()
{
    DataTable dataTable = new DataTable();

    //create columns
    for (int i = 0; i < DG_dataGridView.Columns.Count; i++)
    {
        dataTable.Columns.Add("column"+i.ToString());
    }

    //populate data
    foreach (GridViewRow row in DG_dataGridView.Rows)
    {
        DataRow dr = dataTable.NewRow();
        for(int j = 0; j < DG_dataGridView.Columns.Count; j++)
        {
            dr["column" + j.ToString()] = row.Cells[j].Text;
        }

        dataTable.Rows.Add(dr);
    }

    //write to file
    string dataFile = "c:\test.xml"
    dataTable.DataSet.WriteXml(dataFile);
}

并使用它:

//I want to change column name than save it to file
var column = DG_dataGridView.Columns[ColumnIndex];

column.Name = ColumnName;
column.HeaderText = ColumnName;

//write to file
WriteToFile();

Code reference