Search code examples
c#datagridviewexporttext-filesexport-to-text

C# Save DataGridView to Text File


I'm currently attempting to use datagridview for the first time, I have managed to do many things with it so far (such as importing text files) however, I have trouble when attempting to save the datagridview's contents to a text file.

The output I'm currently getting is:

    0,
 Cat,
 Yes,
10,
20,
30,
40,
50,
1,
 Dog,
 No,
10,
20,
30,
40,
50,

I want the export to look like this:

0, Cat, Yes, 10, 20, 30, 40, 50
1, Dog, No, 10, 20, 30, 40, 50
etc.

This is the code I'm currently using:

using (TextWriter tw = new StreamWriter("example.txt"))
{
    for(int i = 0; i < dataGridView1.Rows.Count - 1; i++)
                {
                    for(int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        tw.WriteLine($"{dataGridView1.Rows[i].Cells[j].Value.ToString()},");
                    }
                }
    }

Anyone here able to help me with this issue? Thank you!


Solution

  • Try the following changes tw.Write() insted of tw.WriteLine():

    using (TextWriter tw = new StreamWriter("example.txt"))
    {
        for(int i = 0; i < dataGridView1.Rows.Count - 1; i++)
        {
             for(int j = 0; j < dataGridView1.Columns.Count; j++)
             {
                 tw.Write($"{dataGridView1.Rows[i].Cells[j].Value.ToString()}");
    
                 if(!j == dataGridView1.Columns.Count - 1)
                 {
                    tw.Write(",");
                 }
             }
             tw.WriteLine();
         }
    }