Burak Seyhan

Burak Seyhan

  • NA
  • 321
  • 30.2k

How to export datagrid to cvs file on WPF

Mar 20 2015 7:56 AM
StreamWriter sw = new StreamWriter("c:\\gridview.csv");
// now add the gridview header in csv file suffix with "," delimeter except last one
for (int i = 0; i < grid.Columns.Count; i++)
{
sw.Write(grid.Columns[i].Header.ToString());
if (i != grid.Columns.Count)
{
sw.Write(",");
}
}
// add new line
sw.Write(sw.NewLine);
// iterate through all the rows within the gridview
foreach (GridView dr in grid.SetValue(grid.Rows.Count)  // grid.Rows does not work 
{
// iterate through all colums of specific row
for (int i = 0; i < GridView1.Columns.Count; i++)
{
// write particular cell to csv file
sw.Write(dr.Cells[i].Text);
if (i != GridView1.Columns.Count)
{
sw.Write(",");
}
}
// write new line
sw.Write(sw.NewLine);
}
// flush from the buffers.
sw.Flush();
// closes the file
sw.Close();
 
 
 
Rows.Count doesnt work how can i fix it?