我是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
对象时,虽然我看到GUI
和dataGridView
对象中的更改
答案 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();