[Solved] Write a table structure in a Text file and Print afterwards through C# [closed]


While I think a lot of the other commenters are correct in their opinion of the question, I think this still deserves an attempt at an answer.

So, in MySQL, when you do a dump of rows from the command line, it creates a visual table using ASCII text that I always like. It looks like this

+-------+-------+-------+-------+
| Col 1 | col 2 | Col 3 | Col 4 |   
+-------+-------+-------+-------+
|   1   |   2   |  red  |  dog  |
+-------+-------+-------+-------+
|   1   |   4   |  blue |  cat  |
+-------+-------+-------+-------+
|    2  |   9   |  red  | bird  |
+-------+-------+-------+-------+

Now the other commenters are correct that we do need to learn to solve stuff on our own, so I will also point you in the correct direction for creating the table but not give the actual code.

To build the table you want to use the StringBuilder class to create strings based on the table values, making sure that the spacing is always correct. Also, when you output it, if it isn’t plain text in a monospaced font, the table structure will not look right.

And just to stat you off, assuming by “table” you mean an ADO.NET DataTable, I would do this.

var maxLength = 0;
foreach(DataColumn c in table.Columns)
{
    //if the length of the column name is greater than the current max length
    //update the max length
    maxLength = maxLength < c.Name.Length ? c.Name.Length : maxLength;
}
//add some padding
maxLength = maxLength + 2;

var sb = new StringBuilder();

//create the top row
foreach(DataColumn c in table.Columns)
{
   sb.AppendFormat("+{0}+", new String('-',maxLength));
}
sb.AppendLine();

//create the column names
foreach(DataColumn c in Table.Columns)
{
   sb.AppendFormat("|{0}|", c.Name.PadLeft('0', maxLength));
}
sb.AppendLine();

//create the bottom of the column headers same as the top
foreach(DataColumn c in table.Columns)
{
   sb.AppendFormat("+{0}+", new String('-',maxLength));
}
sb.AppendLine();

This is all off the top of my head, so I probably have a typo or a tiny logic mistake in there somewhere, I am sure. But play around with the code and get to understand what it is doing and you will have the tools necessary to be able to solve your problem.

1

solved Write a table structure in a Text file and Print afterwards through C# [closed]