I want to output to my console a nicely formatted table with data from SqlDataReader.
I found this answer here on SO with a nice class to do all the work, however, I need some help to implement the SqlDataReader part.
My code for printing out the table looks like this:
SqlDataReader data = getCommentsFromDB();
int value = 997;
string[,] arrValues = new string[5, 5];
for (int i = 0; i < arrValues.GetLength(0); i++)
{
for (int j = 0; j < arrValues.GetLength(1); j++)
{
value++;
arrValues[i, j] = value.ToString();
}
}
ArrayPrinter.PrintToConsole(arrValues);
Console.ReadLine();
getCommentsFromDB looks like this:
SqlConnection conn = dal.connectDatabase();
conn.Open();
cmd = new SqlCommand(@"SELECT * FROM GuestBook", conn);
rdr = cmd.ExecuteReader();
return rdr;
If you need anything else, please tell.
UPDATE
I got it a bit further. However, now I am getting this nasty error:
Error: {0}System.NullReferenceException: Object reference not set to an instance of an object.
at GuestBook.ArrayPrinter.GetMaxCellWidth(String[,] arrValues) in \GuestBook\GuestBook\ArrayPrinter.cs:line 39
at GuestBook.ArrayPrinter.GetDataInTableFormat(String[,] arrValues) in \GuestBook\GuestBook\ArrayPrinter.cs:line 60
at GuestBook.ArrayPrinter.PrintToConsole(String[,] arrValues) in \GuestBook\GuestBook\ArrayPrinter.cs:line 117
at GuestBook.StudentManager.showAllComments() in \GuestBook\GuestBook\StudentManager.cs:line 49
at GuestBook.ConsoleGUI.start(String[] args) in \GuestBook\GuestBook\ConsoleGUI.cs:line 28
at GuestBook.Program.Main(String[] args) in \GuestBook\GuestBook\Program.cs:line 20
With my experience, I would say something is wrong with the class I am using. Maybe it needs an update?
I am running in VS2012 and C#.NET 4.0
Update 2
My data prints out like this:
-------------------------------------------------------------------------
| Column 1 | Column 2 | Column 3 | Column 4 |
-------------------------------------------------------------------------
| X | | | |
| | X | | |
| | | X | |
| | | | X |
-------------------------------------------------------------------------
and not in a single row.
My code so far:
public void showAllComments()
{
SqlDataReader reader = getCommentsFromDB();
string[,] arrValues = new string[5, 3];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
if (!reader.Read()) break; //no more rows
{
arrValues[i, j] = reader[j].ToString();
}
}
}
ArrayPrinter.PrintToConsole(arrValues);
}
Also, I would like it to expand vertically to contain all the data in the database.