none
Create a table by C# console Application RRS feed

  • Question

  • I want to create a table by C# console Application. how can i create this and whitch code i should use.

    thanks. Saeeddoe.

    Friday, August 6, 2010 6:34 PM

Answers

  • Hi SAEEDDOE,

     

    Welcome to MSDN Forum!

     

    The demo following will help us to print a 2D array. We only give this program a 2D array, it can help us to finish remain things. It will calculate the count of the column, so we don’t hard coding this thing into our program.

     

    Well, let’s see the codes and the annotation through the codes.

     

        class UI_Format
        {
            public enum Align { Left, Right };
            private string[] headers;
            private Align CellAlignment = Align.Left;
            private int tableYStart = 0;
            /// <summary>
            /// The last line of the table (gotton from Console.CursorTop). -1 = No printed data
            /// </summary>
            public int LastPrintEnd = -1;
     
            /// <summary>
            /// Helps create a table
            /// </summary>
            /// <param name="TableStart">What line to start the table on.</param>
            /// <param name="Alignment">The alignment of each cell\'s text.</param>
            public UI_Format(int TableStart, Align Alignment, string[] headersi)
            {
                headers = headersi;
                CellAlignment = Alignment;
                tableYStart = TableStart;
            }
            public void ClearData()
            {
                //Clear Previous data
                if (LastPrintEnd != -1) //A set of data has already been printed
                {
                    for (int i = tableYStart; i < LastPrintEnd; i++)
                    {
                        ClearLine(i);
                    }
                }
                LastPrintEnd = -1;
            }
            public void RePrint(ArrayList data)
            {
                //Set buffers
                if (data.Count > Console.BufferHeight)
                    Console.BufferHeight = data.Count;
                //Clear Previous data
                ClearData();
     
                Console.CursorTop = tableYStart;
                Console.CursorLeft = 0;
                if (data.Count == 0)
                {
                    Console.WriteLine("No Records");
                    LastPrintEnd = Console.CursorTop;
                    return;
                }
     
                //Get max lengths on each column
                int ComWidth = ((string[])data[0]).Length * 2 + 1;
                int[] ColumnLengths = new int[((string[])data[0]).Length];
     
                foreach (string[] row in data)
                {
                    for (int i = 0; i < row.Length; i++)
                    {
                        if (row[i].Length > ColumnLengths[i])
                        {
                            ComWidth -= ColumnLengths[i];
                            ColumnLengths[i] = row[i].Length;
                            ComWidth += ColumnLengths[i];
                        }
                    }
                }
                //Don't forget to check headers
                for (int i = 0; i < headers.Length; i++)
                {
                    if (headers[i].Length > ColumnLengths[i])
                    {
                        ComWidth -= ColumnLengths[i];
                        ColumnLengths[i] = headers[i].Length;
                        ComWidth += ColumnLengths[i];
                    }
                }
     
     
                if (Console.BufferWidth < ComWidth)
                    Console.BufferWidth = ComWidth + 1;
                PrintLine(ComWidth);
                //Print Data
                bool first = true;
                foreach (string[] row in data)
                {
                    if (first)
                    {
                        //Print Header
                        PrintRow(headers, ColumnLengths);
                        PrintLine(ComWidth);
                        first = false;
                    }
                    PrintRow(row, ColumnLengths);
                    PrintLine(ComWidth);
                }
                LastPrintEnd = Console.CursorTop;
            }
     
            private void ClearLine(int line)
            {
                int oldtop = Console.CursorTop;
                Console.CursorTop = line;
                int oldleft = Console.CursorLeft;
                Console.CursorLeft = 0;
                int top = Console.CursorTop;
     
                while (Console.CursorTop == top)
                { Console.Write(" "); }
                Console.CursorLeft = oldleft;
                Console.CursorTop = oldtop;
            }
     
            private void PrintLine(int width)
            {
                Console.WriteLine(new string('-', width));
            }
     
            private void PrintRow(string[] row, int[] Widths)
            {
                string s = "|";
                for (int i = 0; i < row.Length; i++)
                {
                    if (CellAlignment == Align.Left)
                        s += row[i] + new string(' ', Widths[i] - row[i].Length + 1) + "|";
                    else if (CellAlignment == Align.Right)
                        s += new string(' ', Widths[i] - row[i].Length + 1) + row[i] + "|";
                }
                if (s == "|")
                    throw new Exception("PrintRow input must not be empty");
     
                Console.WriteLine(s);
            }
        }

     

    class Program
        {
            static void Main(string[] args)
            {
                string[] headers = new string[] { "Atomic Number""Abreviation""Name""Atomic Weight" };
                UI_Format ConsoleFormatter = new UI_Format(3, UI_Format.Align.Left, headers);
                #region DATA
                string[][] data = new string[][] {
                        new string[] {
                        "89""Ac""Actinium""227"},
                        new string[] {
                        "13""Al""Aluminum""26.98154"},
                        new string[] {
                        "56""Ba""Barium""137.33"},
                        new string[] {
                        "4""Be""Beryllium""9.01218"},
                        new string[] {
                        "83""Bi""Bismuth""208.9804"},
                        };
                #endregion
                ArrayList arr = new ArrayList(data);
                ConsoleFormatter.RePrint(arr); //Get data variable from the link in the description
                Console.ReadLine();
            }
        }

     

     

    If there’s anything unclear please feel free let me know, and I am glad to help you.

     

    Regards,

    Mike

    -------------------------------------------------------------------

    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to the others community members reading the thread.

    Wednesday, August 11, 2010 3:36 AM
    Moderator

All replies

  • What kind of table do you want?  Do you just want a data structure to hold some objects?  If that's the case, the System.Collections.Generic namespace has quite a few that should meet your needs.
    Friday, August 6, 2010 6:43 PM
  •  
    "SAEEDDOE" wrote in message news:254ac452-83bd-489d-8ce2-462a2c9acabc...

    I want to create a table by C# console Application. how can i create this and whitch code i should use.

     

    My response ------------------------------------------------------------------------------------------------------------------------------------------

    Have you ever heard of 'objects'? Have you ever heard of using a collection of objects in a List<T>? 

    http://msdn.microsoft.com/en-us/library/w86s7x04(VS.80).aspx

    http://en.csharp-online.net/Understanding_Generics%E2%80%94Examining_the_List%28T%29_Type

    http://dotnetperls.com/list

     

    Friday, August 6, 2010 7:21 PM
  • Heres a data table. Apologies in advance for the lousy ASCII graphics.

    DataTable myTable = new DataTable();
          DataColumn column1 = new DataColumn("Column1", Type.GetType("System.Int32"));
          DataColumn column2 = new DataColumn("Column2", Type.GetType("System.String"));
          myTable.Columns.Add( column1) ;
          myTable.Columns.Add(column2);
          for(int i = 1; i < 30; i ++)
          {
            DataRow newRow = myTable.NewRow();
            newRow[0] = i;
            newRow[1] = i.ToString();
            myTable.Rows.Add(newRow);
          }
          StringBuilder sb = new StringBuilder();
          sb.Append("|------------------|");
          sb.Append(Environment.NewLine);
          sb.Append(myTable.Columns[0].ColumnName);
          sb.Append("  | ");
          sb.Append(myTable.Columns[1].ColumnName);
          sb.Append(Environment.NewLine);
          foreach(DataRow dr in myTable.Rows )
          {
            sb.Append(Convert.ToString( dr[0]));
            sb.Append(" |  ");
            sb.Append(dr[1].ToString());
            sb.Append(Environment.NewLine);
          }
          sb.Append(Environment.NewLine);
          sb.Append("------------------");
          MessageBox.Show(sb.ToString());
    

     

    • Proposed as answer by Lentucky Sunday, August 8, 2010 4:08 PM
    Friday, August 6, 2010 7:24 PM
  • I mean that how can I creat some lines verrtically and horizontaly to shape a table fo example to creat horizontal Line i can write the folowing Code: console.write("-------------------------------------"); but fo drowing this line as vertical which command is needed? thanks a lot.
    Sunday, August 8, 2010 1:48 PM
  •  Console.WriteLine("--------------------");
     Console.WriteLine("|                  |");
     Console.WriteLine("|                  |");
     Console.WriteLine("|                  |");
     Console.WriteLine("|                  |");
     Console.WriteLine("--------------------");
    Sunday, August 8, 2010 11:12 PM
  • That's one option, another is to use the Console.Top and Console.Left properties to write each character out one at a time.

    For example:

    public void writeVerticalLine(char c, int x, int, y, int length)
    {
     for(int i = 0; i < length; i++)
     {
      Console.Left = x;
      Console.Top = y + length;
      Console.Write(c);
     }
    }
    

    Not tested, but that should write out the character c in a vertical line starting at the x/y coords given with a length of the given length.  It would be easy enough to alter that to make a horizontal line.  To do that just set the left to be x + length and the top to be just y.

    Doing this as opposed to Louis's suggestion would prevent the data inside of the table from being overwritten (which may or may not be what you want).

    • Proposed as answer by N8iv Wednesday, February 3, 2016 9:23 PM
    Monday, August 9, 2010 3:22 PM
  • Just a quick observation,

    DataTable myTable = new DataTable();
    DataColumn column1 = new DataColumn("Column1", Type.GetType("System.Int32"));
    DataColumn column2 = new DataColumn("Column2", Type.GetType("System.String"));
    myTable.Columns.Add( column1) ;
    myTable.Columns.Add(column2);
    
    Could be reduced to this:

    DataTable myTable = new DataTable();
    mytable.Columns.Add("Column1", typeOf(Int32));
    mytable.Columns.Add("Column2", typeOf(String));
    
    

    And this:

    for(int i = 1; i < 30; i ++)
       {
        DataRow newRow = myTable.NewRow();
        newRow[0] = i;
        newRow[1] = i.ToString();
        myTable.Rows.Add(newRow);
       }
    
    

    Could be reduced to this:

    for(int i = 1; i < 30; i ++)  
       myTable.Rows.Add(i, i.ToString());
       
    
    


    John Grove - DSS, Senior Software Engineer
    Monday, August 9, 2010 5:49 PM
  • Hi SAEEDDOE,

     

    Welcome to MSDN Forum!

     

    The demo following will help us to print a 2D array. We only give this program a 2D array, it can help us to finish remain things. It will calculate the count of the column, so we don’t hard coding this thing into our program.

     

    Well, let’s see the codes and the annotation through the codes.

     

        class UI_Format
        {
            public enum Align { Left, Right };
            private string[] headers;
            private Align CellAlignment = Align.Left;
            private int tableYStart = 0;
            /// <summary>
            /// The last line of the table (gotton from Console.CursorTop). -1 = No printed data
            /// </summary>
            public int LastPrintEnd = -1;
     
            /// <summary>
            /// Helps create a table
            /// </summary>
            /// <param name="TableStart">What line to start the table on.</param>
            /// <param name="Alignment">The alignment of each cell\'s text.</param>
            public UI_Format(int TableStart, Align Alignment, string[] headersi)
            {
                headers = headersi;
                CellAlignment = Alignment;
                tableYStart = TableStart;
            }
            public void ClearData()
            {
                //Clear Previous data
                if (LastPrintEnd != -1) //A set of data has already been printed
                {
                    for (int i = tableYStart; i < LastPrintEnd; i++)
                    {
                        ClearLine(i);
                    }
                }
                LastPrintEnd = -1;
            }
            public void RePrint(ArrayList data)
            {
                //Set buffers
                if (data.Count > Console.BufferHeight)
                    Console.BufferHeight = data.Count;
                //Clear Previous data
                ClearData();
     
                Console.CursorTop = tableYStart;
                Console.CursorLeft = 0;
                if (data.Count == 0)
                {
                    Console.WriteLine("No Records");
                    LastPrintEnd = Console.CursorTop;
                    return;
                }
     
                //Get max lengths on each column
                int ComWidth = ((string[])data[0]).Length * 2 + 1;
                int[] ColumnLengths = new int[((string[])data[0]).Length];
     
                foreach (string[] row in data)
                {
                    for (int i = 0; i < row.Length; i++)
                    {
                        if (row[i].Length > ColumnLengths[i])
                        {
                            ComWidth -= ColumnLengths[i];
                            ColumnLengths[i] = row[i].Length;
                            ComWidth += ColumnLengths[i];
                        }
                    }
                }
                //Don't forget to check headers
                for (int i = 0; i < headers.Length; i++)
                {
                    if (headers[i].Length > ColumnLengths[i])
                    {
                        ComWidth -= ColumnLengths[i];
                        ColumnLengths[i] = headers[i].Length;
                        ComWidth += ColumnLengths[i];
                    }
                }
     
     
                if (Console.BufferWidth < ComWidth)
                    Console.BufferWidth = ComWidth + 1;
                PrintLine(ComWidth);
                //Print Data
                bool first = true;
                foreach (string[] row in data)
                {
                    if (first)
                    {
                        //Print Header
                        PrintRow(headers, ColumnLengths);
                        PrintLine(ComWidth);
                        first = false;
                    }
                    PrintRow(row, ColumnLengths);
                    PrintLine(ComWidth);
                }
                LastPrintEnd = Console.CursorTop;
            }
     
            private void ClearLine(int line)
            {
                int oldtop = Console.CursorTop;
                Console.CursorTop = line;
                int oldleft = Console.CursorLeft;
                Console.CursorLeft = 0;
                int top = Console.CursorTop;
     
                while (Console.CursorTop == top)
                { Console.Write(" "); }
                Console.CursorLeft = oldleft;
                Console.CursorTop = oldtop;
            }
     
            private void PrintLine(int width)
            {
                Console.WriteLine(new string('-', width));
            }
     
            private void PrintRow(string[] row, int[] Widths)
            {
                string s = "|";
                for (int i = 0; i < row.Length; i++)
                {
                    if (CellAlignment == Align.Left)
                        s += row[i] + new string(' ', Widths[i] - row[i].Length + 1) + "|";
                    else if (CellAlignment == Align.Right)
                        s += new string(' ', Widths[i] - row[i].Length + 1) + row[i] + "|";
                }
                if (s == "|")
                    throw new Exception("PrintRow input must not be empty");
     
                Console.WriteLine(s);
            }
        }

     

    class Program
        {
            static void Main(string[] args)
            {
                string[] headers = new string[] { "Atomic Number""Abreviation""Name""Atomic Weight" };
                UI_Format ConsoleFormatter = new UI_Format(3, UI_Format.Align.Left, headers);
                #region DATA
                string[][] data = new string[][] {
                        new string[] {
                        "89""Ac""Actinium""227"},
                        new string[] {
                        "13""Al""Aluminum""26.98154"},
                        new string[] {
                        "56""Ba""Barium""137.33"},
                        new string[] {
                        "4""Be""Beryllium""9.01218"},
                        new string[] {
                        "83""Bi""Bismuth""208.9804"},
                        };
                #endregion
                ArrayList arr = new ArrayList(data);
                ConsoleFormatter.RePrint(arr); //Get data variable from the link in the description
                Console.ReadLine();
            }
        }

     

     

    If there’s anything unclear please feel free let me know, and I am glad to help you.

     

    Regards,

    Mike

    -------------------------------------------------------------------

    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to the others community members reading the thread.

    Wednesday, August 11, 2010 3:36 AM
    Moderator
  • Mike, for these types of console printing tools it's really handy to have them accept objects rather than strings, and to use the toString() method.  That way if you have a structure of some other object you don't need to convert it into a string just to print it out (especially if you do it periodically).  However, if the person doesn't want their objects printed out using the tostring method (either because it's not overrided, or because it's just not what they want to print) they can still manually convert it to a string, and calling tostring on a string will just return itself.  It would also prevent runtime exceptions if a non-string object was entered since the arraylist isn't generic.  It's not a huge change, but it's just a nice small alteration that improves usibility.
    Wednesday, August 11, 2010 4:12 PM
  • Hi s3rvy,

     

    Thanks for your opinion. And the opinion is very good. I like your mind.

     

    We print anything to the Console is also a string not a complicated type. We also print a string from the property of the complicated object.

     

    And if we want print an object like you said. We can make a method to read an object as a record, and then print each property to the Console because of the basic part of a complicated type is such as, int, string, float. We can print these values to the console easily.

     

    So if we want to use this code to print a complicated type, we only need to print each property. And we also can put these properties into the list, if we don’t want to modify the codes above.

     

    We print an object’s information is also use this way, isn’t it?

     

    It is not complicate, and this is only a part of OOP thinking.

     

    I’m glad to talk about this with you. Thank you, s3rvy.

     

    If there’s anything unclear please feel free let me know, and I am glad to help you.

     

    Have a nice day!

    Mike

    -------------------------------------------------------------------

    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to the others community members reading the thread.

    Thursday, August 12, 2010 3:25 AM
    Moderator
  • I created a simple utility to print data as tables to the console.  You can install the NuGet package with: 

    PM> Install-Package TableFormatter

    You can see an example of it in action here

    Sunday, November 23, 2014 7:01 PM
  • That's one option, another is to use the Console.Top and Console.Left properties to write each character out one at a time.

    For example:

    public void writeVerticalLine(char c, int x, int, y, int length)
    {
     for(int i = 0; i < length; i++)
     {
      Console.Left = x;
      Console.Top = y + length;
      Console.Write(c);
     }
    }
    

    Not tested, but that should write out the character c in a vertical line starting at the x/y coords given with a length of the given length.  It would be easy enough to alter that to make a horizontal line.  To do that just set the left to be x + length and the top to be just y.

    Doing this as opposed to Louis's suggestion would prevent the data inside of the table from being overwritten (which may or may not be what you want).

    This could be used for falling text, like in the Matrix Movie? I've been toying with the idea of coding the falling text for quite some time now. The other option I was thinking of was creating a DataTable Instance in a console application.
    Friday, April 3, 2015 1:23 AM