Extra rows when exporting Datagridview to .csv

Mazon

New member
Joined
Apr 23, 2019
Messages
1
Programming Experience
Beginner
Hi!

I have a application that I can open a csv file with, then modify it and then export it back to my computer.
it works well and all but there's one problem with it.
When I export the datagridview as csv it creates two plank extra rows on the bottom of the csv file.
I have tried pretty much everything that I can do but it still brings the rows.

My code for the export looks like this:

C#:
private void btnExport_Click(object sender, EventArgs e)
{
    // Don't save if no data is returned
    if (dataGridView1.Rows.Count ==0)
    {
        return;
    }

    StringBuilder sb = new StringBuilder();
    sb.AppendLine(string.Join(",", dataGridView1.Columns.Cast<DataGridViewColumn>().Select(x => $"\"{x.Name}\"")));
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (!row.IsNewRow)
        {
            sb.AppendLine(string.Join(",", row.Cells.Cast<DataGridViewCell>().Select(c => $"\"{c.Value ?? ""}\"")));
        }
    }

    // Load up the save file dialog with the default option as saving as a .csv file.
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Filter = "CSV files (*.csv)|*.csv";

    if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        // If they've selected a save location...
        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(sfd.FileName, false))
        {
            // Write the stringbuilder text to the the file.
            sw.WriteLine(sb.ToString());
        }
    }


Any help is appriciated, Thanks.

-Mazon
 
Last edited by a moderator:
You are calling AppendLine when you create the StringBuilder and then you call WriteLine when writing to the file. Why do you need to write a line break to the file if you have already written line breaks into the text?
 
Even if you use Write instead of WriteLine, you are still writing a line break at the end of each record, so your file will still have an empty line at the end. That's not really a problem because any CSV reader worth its salt will correctly read that as the end of the data and not add a blank record. If you want to avoid that though, don't write a line break at the end of each record. Instead, write a line break to the beginning of each record except the first.
 
Back
Top Bottom