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.