2

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!

ACƎ
  • 23
  • 1
  • 1
  • 3

6 Answers6

9

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();
     }
}
IceCode
  • 1,466
  • 13
  • 22
  • This works great, however I do have a comma at the end of each line: `0, Cat, Yes, 10, 20, 30, 40, 50, 1, Dog, No, 10, 20, 30, 40, 50,` is there a way to remove those end ones? Cheers! – ACƎ May 14 '19 at 21:37
  • I have added changes to my answer. Please test it and let me know. – IceCode May 14 '19 at 21:59
  • Sadly it didn't work, the commas are still appearing on the end. I also had to change `if(!j == dataGridView1.Columns.Count)` to `if(j != dataGridView1.Columns.Count)` – ACƎ May 14 '19 at 22:11
  • Ahh sorry it should be like `if(!j == dataGridView1.Columns.Count - 1)` – IceCode May 14 '19 at 22:17
2

So, DGV to Text file? This is how I do it.

private void button1_Click(object sender, EventArgs e)
        {
            //This line of code creates a text file for the data export.
            System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\\your_path_here\\sample.txt");
            try
            {
                string sLine = "";

                //This for loop loops through each row in the table
                for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
                {
                    //This for loop loops through each column, and the row number
                    //is passed from the for loop above.
                    for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
                    {
                        sLine = sLine + dataGridView1.Rows[r].Cells[c].Value;
                        if (c != dataGridView1.Columns.Count - 1)
                        {
                            //A comma is added as a text delimiter in order
                            //to separate each field in the text file.
                            //You can choose another character as a delimiter.
                            sLine = sLine + ",";
                        }
                    }
                    //The exported text is written to the text file, one line at a time.
                    file.WriteLine(sLine);
                    sLine = "";
                }

                file.Close();
                System.Windows.Forms.MessageBox.Show("Export Complete.", "Program Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (System.Exception err)
            {
                System.Windows.Forms.MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                file.Close();
            }
        }
ASH
  • 20,759
  • 19
  • 87
  • 200
1

Use tw.Write() instead of tw.WriteLine() until you are finished with all but the last column for the row, then you tw.WriteLine() on the last column data to end the line.

Terry Tyson
  • 629
  • 8
  • 18
1

I don't work in C#, but often use these forums as a reference. I develop interfaces for industrial applications. Anyway, the simplest way to do this is through the clipboard. Use the SelectAll() method on your DGV, Throw that DGV data into the Clipboard with the Clipboard.SetDataObject() method, use the File.WriteAllText(), and Clipboard.GetText() methods to write the clipboard text to a file. My code is below. You will notice I have to write out everything from it's namespace so I apologize for it not being exactly how C# is. Note: If you want to make a csv file, DGVs view cell breaks as horizontal tabs (ascii 9). You can do a replace() method for commas. Note: DGV.ClearSelection() is a nice way to finish it off. Note: you may have to enable ClipboardCopyMode on your DGV.

DataGridView1.SelectAll();
System.Windows.Forms.Clipboard.SetDataObject(DataGridView1.GetClipboardContent());
System.IO.File.WriteAllText("File.txt",System.Windows.Forms.Clipboard.GetText());
Birminghamilton
  • 131
  • 2
  • 5
0

With the following code you can save and restore the content of every dataGridView.

How to do it:

string sContent = "";
private void btnSaveDataGridViewContent_Click(object sender, EventArgs e)
{
    sContent = ReadStringFromDataGridView(ref dataGridView1);
    [Write sContent to File/Database/Whatever]
}

private void btnRestoreDataGridViewContent_Click(object sender, EventArgs e)
{
    [Read sContent from File/Database/Whatever]
    WriteStringToDataGridView(ref dataGridView1, sContent);
}

Helper functions:

string ReadStringFromDataGridView(ref DataGridView MyDataGridView)
{
    string sContent = "";
    for (int row = 0; row<MyDataGridView.RowCount; row++)
    {
        if (row > 0) sContent += "\r";
        for (int col = 0; col<MyDataGridView.ColumnCount; col++)
        {
            if (col > 0) sContent += ";";
            sContent += MyDataGridView[col, row].Value;
        }
    }
    return sContent;
}

void WriteStringToDataGridView(ref DataGridView MyDataGridView, string sContent)
{
    MyDataGridView.Rows.Clear();
    string[] Rows = sContent.Split("\r".ToCharArray());
    for (int row=0; row<Rows.Length; row++)
    {
        MyDataGridView.RowCount = Rows.Length;
        string[] Cols = Rows[row].Split(";".ToCharArray());
        for (int col=0; col<Cols.Length; col++)
        {
            MyDataGridView[col, row].Value = Cols[col];
        }
    }
}
Michael Hutter
  • 1,064
  • 13
  • 33
0
string file = "C:\\Users\\Sangeeth\\Desktop\\Excel.txt";            
        using (TextWriter tw = new StreamWriter(file))
        {
            int i, j = 0;
            for(i = 0; i < dataGridView1.Rows.Count -1; i++)
            {
                for (j = 0; j < dataGridView1.Columns.Count; j++)
                {

                    tw.Write($"{dataGridView1.Rows[i].Cells[j].Value.ToString()}");
                    tw.Write(",");
                }

                tw.WriteLine(" ");
            }
        }
pradeep
  • 1
  • 1
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 09 '23 at 02:08