In this article we will learn how to display the Data table in the form of table in console application.
We will create the console application to do this.
We do following things to achieve this,
Step 1: Console.WriteLine() statement creates the table's header by using the Console.WriteLine() method with string formatting.
Step 2: Second Console.WriteLine() statement creates a separator row by using the "-" character to match the width of each column.
Step 3: Finally, the third Console.WriteLine() statement loops through the DataTable rows and displays each row's data by using string formatting to align the data in each column.
Here is the complete example:
using System;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Job", typeof(string));
dt.Rows.Add(1, "Chakrapani", "SE");
dt.Rows.Add(2, "Shraddha", "TL");
dt.Rows.Add(3, "Shreshta", "HR");
Console.WriteLine("-----------WELCOME TO USER DATA-------------");
Console.WriteLine("|{0}|", new string('-', 33));
Console.WriteLine("| {0,-5} | {1,-15} | {2,-5} |", "Id", "Name", "Job");
Console.WriteLine("|{0}|{1}|{2}|", new string('-', 7), new string('-', 17), new string('-', 7));
foreach (DataRow row in dt.Rows)
{
Console.WriteLine("| {0,-5} | {1,-15} | {2,-5} |", row["Id"], row["Name"], row["Job"]);
}
Console.WriteLine("|{0}|", new string('-', 33));
Console.ReadKey();
}
}
}