User1204501
User1204501

Reputation: 831

Writing to a text file from DataGridView in C# windows form

I want to write the data from my DataGridView to a textfile.

The following code writes the data but it is not formatted correctly.

StreamWriter sW = new StreamWriter(dirLocationString);

string lines = "";

for (int row = 0; row< numRows1; row++){
     for (int col = 0; col < 4; col++)
         {

          lines = lines + " " + dataGridView1.Rows[row].Cells[col].Value.ToString();

         }

      sW.WriteLine(lines);
}

   sW.Close();   

I want the output format to be like:

AAAA, BBBB, CCCC, DDDD 

But instead it displays the following:

AAAA BBBB CCCC DDDD
AAAA BBBB CCCC DDDD AAAA BBBB CCCC DDDD
AAAA BBBB CCCC DDDD AAAA BBBB CCCC DDDD AAAA BBBB CCCC DDDD
and so on..

Upvotes: 0

Views: 17729

Answers (2)

Adam White
Adam White

Reputation: 3390

Unfortunately looping through rows and columns is prone to errors and not very succinct. Here is a little hack that takes advantage of Windows.Forms.Clipboard and DataGridView.GetClipboardContent() to do all the dirty work for you. DataGridView.GetClipboardContent() returns all the selected data cells as a DataObject, which is how the Clipboard class is able to store different types of data and formatting. The contents of the clipboard are then written to a file using the File class. You say you want a text file, but I see commas the example of your desired output, so I am assuming you would like a CSV file. You can also write out a text file by changing the Clipboard.GetText parameter.

void SaveDataGridViewToCSV(string Filename)
{
    // Choose whether to write header. Use EnableWithoutHeaderText instead to omit header.
    dataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithAutoHeaderText;
    // Select all the cells
    dataGridView1.SelectAll();
    // Copy (set clipboard)
    Clipboard.SetDataObject(dataGridView1.GetClipboardContent());
    // Paste (get the clipboard and serialize it to a file)
    File.WriteAllText(Filename,Clipboard.GetText(TextDataFormat.CommaSeparatedValue));
}

Please note that an object must be serializable for it to be put on the Clipboard.

For a tab-delimited file, use the TextDataFormat.Text enum in your call to Clipboard.GetText(). You can also output your DataGridView as HTML by using TextDataFormat.Html instead of TextDataFormat.CommaSeparatedValue, but there is extra header data you have to parse out.

Hope this helps.

Upvotes: 1

Pascalz
Pascalz

Reputation: 2378

Init lines in first loop :

StreamWriter sW = new StreamWriter(dirLocationString);

for (int row = 0; row< numRows1; row++){
    string lines = "";
    for (int col = 0; col < 4; col++)
    {
        lines += (string.IsNullOrEmpty(lines) ? " " : ", ") + dataGridView1.Rows[row].Cells[col].Value.ToString();
    }

    sW.WriteLine(lines);
}

sW.Close(); 

Upvotes: 3

Related Questions