1

I have a datatable (dt) which, when I put into a DataGridView, is automatically and nicely formatted.

How can I "write" this table/view to a txt file? Without looping through and doing all the formatting myself.

Is there any built-in functionality?

dt.WriteXml(report,XmlWriteMode.IgnoreSchema);

The above unfortunately gives all the XML structure and tags.

I would like some similar to the "GridView".

ManInMoon
  • 6,795
  • 15
  • 70
  • 133
  • http://stackoverflow.com/questions/11749812/write-rows-from-datatable-to-text-file and http://stackoverflow.com/questions/17398019/how-to-convert-datatable-to-json-in-c-sharp would go into that direction but in both you iterate through things – Thomas Oct 13 '15 at 09:28
  • Possible duplicate of [Exporting datagridview to csv file](http://stackoverflow.com/questions/9943787/exporting-datagridview-to-csv-file) – ASh Oct 13 '15 at 10:34

2 Answers2

1

Based on Adam Rakaska's approach (from Exporting datagridview to csv file):

Just need to change format to "Text":

dataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
dataGridView1.SelectAll();
Clipboard.SetDataObject(dataGridView1.GetClipboardContent());
report.WriteLine( Clipboard.GetText(TextDataFormat.Text));

This saves having to code all the formatting oneself.

Community
  • 1
  • 1
ManInMoon
  • 6,795
  • 15
  • 70
  • 133
0

Is there any built-in functionality?

NO, there is no built-in functionality

This will probably do the trick for you

public static void DataTable2TXT(DataTable dt, string fp)
{
    int i = 0;
    StreamWriter sw = null;
    sw = new StreamWriter(fp, false);
    for (i = 0; i < dt.Columns.Count - 1; i++)
    {
        sw.Write(dt.Columns[i].ColumnName + ";");
    }
    sw.Write(dt.Columns[i].ColumnName);
    sw.WriteLine();

    foreach (DataRow row in dt.Rows)
    {
        object[] array = row.ItemArray;
        for (i = 0; i < array.Length - 1; i++)
        {
            sw.Write(array[i].ToString() + ";");
        }
        sw.Write(array[i].ToString());
        sw.WriteLine();
    }
    sw.Close();
}
Shweta Pathak
  • 775
  • 1
  • 5
  • 21