Write Contents in a text file in a tabular order using C#
-
11-12-2019 - |
Question
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.
Solution
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);
OTHER TIPS
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();