Hi,
Is there a way to implement csv exporting from a datagrid, using .NET 2.0 Winforms?
Thanks
Hi,
Is there a way to implement csv exporting from a datagrid, using .NET 2.0 Winforms?
Thanks
There's nothing built in, but it's fairly straightforward to do yourself.
// Create the CSV file to which grid data will be exported.
StreamWriter sw = new StreamWriter("~/GridData.txt", false);
DataTable dt = GetDataTable(); // Pseudo code
// First we will write the headers.
List<string> columnNames = new List<string>();
foreach (DataColumn column in dt.Columns)
{
columnNames.Add(column.ColumnName);
}
sw.WriteLine(string.Join(",", columnNames.ToArray()));
// Now write all the rows.
int iColCount = dt.Columns.Count;
foreach (DataRow dr in dt.Rows)
{
List<string> columnData = new List<string>();
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
columnData.Add(dr[i].ToString());
}
}
sw.WriteLine(string.Join(",", columnData.ToArray()));
}
sw.Close();
There are certainly further optimisations and improvements that can be made to this code. I'm not happy with the code that writes out the rows.