- Remove last delimiter (comma)
You already have the number of columns ColumnCount,
therefore, while looping through the columns, a simple check is needed to see if the currentColumn
is “less than” the ColumnCount
-1. If the currentColumn
IS less than ColumnCount
-1, then you need to add the “comma” ,
. If currentColumn
is NOT “less than” ColumnCount
, then this can mean only one thing… this is the last column and instead of adding the comma you want to add a new line.
if (currentCol < ColumnCount - 1) {
textBoxExport.Text += ",";
}
else {
textBoxExport.Text += Environment.NewLine;
}
- Column Headers in CSV file
This will need to be separate from looping through the rows. Before looping through the rows, loop through the columns of the grid and get each columns Name
property. This would be the first line in the CSV file. You can use the same strategy as above to avoid the last comma.
for (int currentCol = 0; currentCol < ColumnCount; currentCol++) {
textBoxExport.Text += dgvCsv1.Columns[currentCol].Name;
if (currentCol < ColumnCount - 1) {
textBoxExport.Text += ",";
}
else {
textBoxExport.Text += Environment.NewLine;
}
}
Lastly, it is unclear why you are using a TextBox
to store the CSV string. I recommend using a StringBuilder.
Below is an example of what is described above.
private void btnSave_Click(object sender, EventArgs e) {
StringBuilder sb = new StringBuilder();
int RowCount = dgvCsv1.RowCount;
int ColumnCount = dgvCsv1.ColumnCount;
// get column headers
for (int currentCol = 0; currentCol < ColumnCount; currentCol++) {
sb.Append(dgvCsv1.Columns[currentCol].Name);
if (currentCol < ColumnCount - 1) {
sb.Append(",");
}
else {
sb.AppendLine();
}
}
// get the rows data
for (int currentRow = 0; currentRow < RowCount; currentRow++) {
if (!dgvCsv1.Rows[currentRow].IsNewRow) {
for (int currentCol = 0; currentCol < ColumnCount; currentCol++) {
if (dgvCsv1.Rows[currentRow].Cells[currentCol].Value != null) {
sb.Append(dgvCsv1.Rows[currentRow].Cells[currentCol].Value.ToString());
}
if (currentCol < ColumnCount - 1) {
sb.Append(",");
}
else {
sb.AppendLine();
}
}
}
}
textBoxExport.Text = sb.ToString();
System.IO.File.WriteAllText(@"D:\Test\DGV_CSV_EXPORT.csv", sb.ToString());
}