1

I want to write contents into a text file from a DatagridView in my application. In my text file, I would like to follow a format like

Column1            Column2              Column3
[Cell1]            [Cell2]              [Cell3]
[Cell1]            [Cell2]              [Cell3]
[Cell1]            [Cell2]              [Cell3]

and so on in a tabular format. How do I efficiently do that as you see I'm bothered about the locations of text as well to bring about a tabular format in a text file (in Notepad).

Should I use char[] but I feel it might not be efficient. Pl guide with an efficient solution.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
stack_pointer is EXTINCT
  • 2,263
  • 12
  • 49
  • 59

2 Answers2

3

I cannot write a complete solution here, but this is your starting point Formatting Types on MSDN,
in particular the paragraph regarding Composite Formatting

The key is string.Format with columns lenght specifiers like

string.Format("{0:D15}{1:D20}", rowColumn1, rowColumn2);
Steve
  • 213,761
  • 22
  • 232
  • 286
0

Here datagridview is the DataGirdView where all the data is present

C:\File.txt 

is the file where all the data is stored.

      string data = String.Empty;
      for (int col = 0; col < datagridview.ColumnCount; col++)
      {
          data += Convert.ToString(datagridview.Columns[col].HeaderText);
      }
      data += "\n";
      for (int i = 0; i < datagridview.RowCount; i++)
        {
            for (int j = 0; j < datagridview.ColumnCount; j++)
            {
                data += Convert.ToString(datagridview.Rows[i].Cells[j].Value);
                data += "\t";
            }
            data += "\n";
        }
        StreamWriter SW;
        SW = File.AppendText(@"C:\File.txt");

        SW.WriteLine(data + Environment.NewLine);
        SW.Close();
MDMalik
  • 3,951
  • 2
  • 25
  • 39