Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Last active October 13, 2024 10:53
Show Gist options
  • Save karenpayneoregon/6248b1cc2e996aa8fd427e10cd0409d1 to your computer and use it in GitHub Desktop.
Save karenpayneoregon/6248b1cc2e996aa8fd427e10cd0409d1 to your computer and use it in GitHub Desktop.
Export unbound DataGridView to CSV file

Useful for quick and dirty utilities, otherwise a bound DataGridView with a BindList is best.

internal record RowRecord(DataGridViewRow Row, string RowItem);
public static class DataGridViewExtensions
{
public static void ExportRows(this DataGridView sender, string fileName, string defaultNullValue = "(empty)")
{
File.WriteAllLines(fileName, sender.Rows.Cast<DataGridViewRow>()
.Where(row => !row.IsNewRow)
.Select(row => new RowRecord(
row, string.Join(",", Array.ConvertAll(row.Cells.Cast<DataGridViewCell>()
.ToArray(), cell => (cell.Value == null) ? defaultNullValue : cell.Value.ToString()))
))
.Select(@row => @row.RowItem));
}
}
internal record RowRecord(DataGridViewRow Row, string RowItem);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment