I'm new to DataGridView
I want to create simple application that read XML
to dataGridview
Edit it than save it back to XML
My Problem is at the saving to DataSet/DataTable this is my code :
//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);
when I view the dataTable
object I see that none of my changes were set although I see the changes in GUI
and dataGridView
object
Remember you're making changes in GridView
not in DataSource
. You will have to traverse the GridView
and generate a new DataTable
.
Create a separate function:
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);
}
and use it:
//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();
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments