Useful for quick and dirty utilities, otherwise a bound DataGridView with a BindList is best.
Last active
October 13, 2024 10:53
-
-
Save karenpayneoregon/6248b1cc2e996aa8fd427e10cd0409d1 to your computer and use it in GitHub Desktop.
Export unbound DataGridView to CSV file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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