How To: Best Way to Draw Table in Console App (C#)

How To: Best way to draw table in console app (C#)

You could do something like the following:

static int tableWidth = 73;

static void Main(string[] args)
{
Console.Clear();
PrintLine();
PrintRow("Column 1", "Column 2", "Column 3", "Column 4");
PrintLine();
PrintRow("", "", "", "");
PrintRow("", "", "", "");
PrintLine();
Console.ReadLine();
}

static void PrintLine()
{
Console.WriteLine(new string('-', tableWidth));
}

static void PrintRow(params string[] columns)
{
int width = (tableWidth - columns.Length) / columns.Length;
string row = "|";

foreach (string column in columns)
{
row += AlignCentre(column, width) + "|";
}

Console.WriteLine(row);
}

static string AlignCentre(string text, int width)
{
text = text.Length > width ? text.Substring(0, width - 3) + "..." : text;

if (string.IsNullOrEmpty(text))
{
return new string(' ', width);
}
else
{
return text.PadRight(width - (width - text.Length) / 2).PadLeft(width);
}
}

How to print List as table in console application?

Your main tool would be

Console.WriteLine("{0,5} {1,10} {2,-10}", s1, s2, s3);  

The ,5 and ,10 are width specifiers. Use a negative value to left-align.

Formatting is also possible:

Console.WriteLine("y = {0,12:#,##0.00}", y);

Or a Date with a width of 24 and custom formatting:

String.Format("Now = {0,24:dd HH:mm:ss}", DateTime.Now);


Edit, for C#6

With string interpolation you can now write

Console.WriteLine($"{s1,5} {s2,10} {s3,-10}");  
Console.WriteLine($"y = {y,12:#,##0.00}");

You don't need to call String.Format() explicitly anymore:

string s = $"Now = {DateTime.Now,24:dd HH:mm:ss}, y = {y,12:#,##0.00}" ;

Format table in C# console application with strings of varying length

You could use the PadLeft string function in c# to achieve what you want

more info here http://msdn.microsoft.com/en-us/library/system.string.padleft(v=vs.71).aspx

Are there any .NET libraries that draw a table in console (textmode)?

This is the one you are looking for
http://www.phpguru.org/static/ConsoleTable.html
or
http://www.phpguru.org/downloads/csharp/ConsoleTable/ConsoleTable.cs

ConsoleTable table = new ConsoleTable();

table.AppendRow(new string[] {"foo", "bar", "jello"});
table.AppendRow(new string[] {"foo", "bar", "jello"});
table.AppendRow(new string[] {"foo", "bar", "jello"});
table.AppendRow(new string[] {"foo", "bar", "jello"});

table.SetHeaders(new string[] {"First Column", "Second Column", "Third Column"});
table.SetFooters(new string[] {"Yabba"});

table.InsertRow(new string[] {"", "ferfr", "frf r"}, 7);
table.PrependRow(new string[] {});

System.Console.Write(table.ToString());

Produces...

+--------------+---------------+--------------+
| First Column | Second Column | Third Column |
+--------------+---------------+--------------+
| | | |
| foo | bar | jello |
| foo | bar | jello |
| foo | bar | jello |
| foo | bar | jello |
| | | |
| | | |
| | | |
| | ferfr | frf r |
+--------------+---------------+--------------+
| Yabba | | |
+--------------+---------------+--------------+

Display results in a table format in C#

Something like this will probably work:

private static void OutputTable(string query, bool showHeader)
{
MySqlConnection conn = GetConn();

MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = query;
MySqlDataReader reader = cmd.ExecuteReader();
int columnCount = reader.FieldCount;

List<List<string>> output = new List<List<string>>();

if (showHeader)
{
List<string> values = new List<string>();
for (int count = 0; count < columnCount; ++count)
{
values.Add(string.Format("{0}", reader.GetName(count)));
}
output.Add(values);
}

while (reader.Read())
{
List<string> values = new List<string>();
for (int count = 0; count < columnCount; ++count)
{
values.Add(string.Format("{0}", reader[count]));
}
output.Add(values);
}
reader.Close();

List<int> widths = new List<int>();
for (int count = 0; count < columnCount; ++count)
{
widths.Add(0);
}

foreach (List<string> row in output)
{
for (int count = 0; count < columnCount; ++count)
{
widths[count] = Math.Max(widths[count], row[count].Length);
}
}

//int totalWidth = widths.Sum() + (widths.Count * 1) * 3;
//Console.SetWindowSize(Math.Max(Console.WindowWidth, totalWidth), Console.WindowHeight);

foreach (List<string> row in output)
{
StringBuilder outputLine = new StringBuilder();

for (int count = 0; count < columnCount; ++count)
{
if (count > 0)
{
outputLine.Append(" ");
}
else
{
outputLine.Append("| ");
}
string value = row[count];
outputLine.Append(value.PadLeft(widths[count]));
outputLine.Append(" |");
}

Console.WriteLine("{0}", outputLine.ToString());
}
}

How to draw Chart based on DataTable from console application?


        //populate dataset with some demo data..
DataSet dataSet = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Counter", typeof(int));
DataRow r1 = dt.NewRow();
r1[0] = "Demo";
r1[1] = 8;
dt.Rows.Add(r1);
DataRow r2 = dt.NewRow();
r2[0] = "Second";
r2[1] = 15;
dt.Rows.Add(r2);
dataSet.Tables.Add(dt);


//prepare chart control...
Chart chart = new Chart();
chart.DataSource = dataSet.Tables[0];
chart.Width = 600;
chart.Height = 350;
//create serie...
Series serie1 = new Series();
serie1.Name = "Serie1";
serie1.Color = Color.FromArgb(112, 255, 200);
serie1.BorderColor = Color.FromArgb(164, 164, 164);
serie1.ChartType = SeriesChartType.Column;
serie1.BorderDashStyle = ChartDashStyle.Solid;
serie1.BorderWidth = 1;
serie1.ShadowColor = Color.FromArgb(128, 128, 128);
serie1.ShadowOffset = 1;
serie1.IsValueShownAsLabel = true;
serie1.XValueMember = "Name";
serie1.YValueMembers = "Counter";
serie1.Font = new Font("Tahoma", 8.0f);
serie1.BackSecondaryColor = Color.FromArgb(0, 102, 153);
serie1.LabelForeColor = Color.FromArgb(100, 100, 100);
chart.Series.Add(serie1);
//create chartareas...
ChartArea ca = new ChartArea();
ca.Name = "ChartArea1";
ca.BackColor = Color.White;
ca.BorderColor = Color.FromArgb(26, 59, 105);
ca.BorderWidth = 0;
ca.BorderDashStyle = ChartDashStyle.Solid;
ca.AxisX = new Axis();
ca.AxisY = new Axis();
chart.ChartAreas.Add(ca);
//databind...
chart.DataBind();
//save result...
chart.SaveImage(@"c:\myChart.png", ChartImageFormat.Png);

Add this declaration on top of your class:

       using System.Windows.Forms.DataVisualization.Charting;

Output table with foreach and format it nice

In this case you should use a for loop. The problem is that you have a two, nested foreach loops.

Be sure that the score list is at least as big as file list, otherwise you may get an index out of range exception. For a completely safe solution you should add a few checks, which I've omitted for clarity.

List<string> _fileNameList = new List<string>();
List<double> _counterFleschScore = new List<double>();

for (var i=0;i<_fileNameList.Count;++i)
{
Console.Write(_fileNameList[i] + "\t\t\t\t");
Console.Write("{0:N1}", _counterFleschScore[i]);
Console.WriteLine("");
}

An improved code would look something like this.

var _fileNameList = new List<string>();
var _counterFleschScore = new List<double>();

var count = Math.Min(_fileNameList.Count, _counterFleschScore.Count);
for (var i=0; i < count; ++i)
{
Console.WriteLine(string.Format("{0}\t\t\t\t{1:N1}", _fileNameList[i], _counterFleschScore[i]));
}

Create a console application to read data from Azure Table Storage using C#

You are missing an parameter-less constructor in your Person class:

Please change the Person class as below:

class Person : TableEntity
{
private int customerID;
private string LocationAreaCode;
private string PersonnelSubAreaCode;
private string PersonStatusCode;

public Person()
{

}

//other code


}

For more details, please refer to this official doc.



Related Topics



Leave a reply



Submit