Link to home
Start Free TrialLog in
Avatar of ybt
ybt

asked on

C# Export DataGridView

Could anybody help how to export DataGridView to a tab delimited text file in C#?
ASKER CERTIFIED SOLUTION
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You can also surely cast the the DataSource property of the grid into a datatable and use this trick: http://emoreau.com/Entries/Articles/2009/04/Using-LINQ-and-XML-Literals-to-transform-a-DataTable-into-a-HTML-table.aspx
Avatar of Aishwarya Shiva Pareek
Aishwarya Shiva Pareek

Try this:

var sb = new StringBuilder();

var headers = dataGridView1.Columns.Cast<DataGridViewColumn>();
sb.AppendLine(string.Join(",", headers.Select(column => "\"" + column.HeaderText + "\"").ToArray()));

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    var cells = row.Cells.Cast<DataGridViewCell>();
    sb.AppendLine(string.Join(",", cells.Select(cell => "\"" + cell.Value + "\"").ToArray()));
}
System.IO.StreamWriter file = new System.IO.StreamWriter(@"\YourFile.csv");
file.WriteLine(sb.ToString());

Open in new window

Avatar of ybt

ASKER

Thank you, it works, others advises is fine, but about coma separated and my particular need was tab delimited file.