1

I have wrote this method which I would like to display as output as a regular table.(For example column names followed by the data) I have not been able to find any method for this. Nor am I able to manipulate the WriteLine to accomplish this. Any ideas?

I am fairly new to programming and C#.

public void ShowQuery()  //to be used with showing data   
{
    try
    {
        SqlDataReader reader = _mySqlCommand.ExecuteReader(); 
        int columnCount = reader.FieldCount;

        while(reader.Read())  //How can I use display results as a normal table like in access?
        {

            for (int i = 0; i < columnCount; i++)
            {
                Console.WriteLine( reader[i]);

            }//end for 
        }//end while
        reader.Close();
        Console.Beep();
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Altaf
  • 399
  • 1
  • 5
  • 15
  • 1
    Best answer: Don't use a console app for this. Console formatting is *not* fun (though it is possible with padding functions). If you want it "like Access", then use windows forms, or even better, WPF. – BradleyDotNET Oct 06 '14 at 20:06
  • I agree with Bradley. You will want to dispose of the SqlDataReader as well..http://stackoverflow.com/questions/16985876/sqlconnection-sqlcommand-sqldatareader-idisposable –  Oct 06 '14 at 20:09
  • where are you declaring this `_mySqlCommand.` can you show in your existing code please – MethodMan Oct 06 '14 at 20:11
  • 3
    What are you trying to learn? How to get data from a database using C# or are you trying to learn how to manipulate the console. If it's to learn how to get data back I would just download [linqPad](http://www.linqpad.net) and then use the dump extension e.g. reader.Dump(); – Conrad Frix Oct 06 '14 at 20:11
  • @DJKRAZE What does that have to do with anything? He's asking how to output the result, not an error with his data query. – BradleyDotNET Oct 06 '14 at 20:12
  • Try this, http://www.hanselman.com/blog/NuGetPackageOfTheWeekMarkdownLogMakesLogFilesMuchPrettier.aspx –  Oct 06 '14 at 20:23

3 Answers3

1

A couple things you should look into:

  • String.PadRight, String.PadLeft, allow you to add spaces until your string is a certain length.

  • format strings, allow you to format your strings more easily. take note, that you can use Console.WriteLine in the same manner as you would String.Format

here's a sample

var s1 = "1983bi".PadLeft(10);
var s2 = "23".PadLeft(10);

Console.WriteLine("{0} | {1}", s1, s2);
Console.WriteLine("{0} | {1}", s2, s1);

Console.ReadKey(false);
  • what does the {} brace mean in this context? Let's say I have 4 columns in my particular data Table, would I need for of these? – Altaf Oct 06 '14 at 20:13
  • 1
    @Altaf the brace are for the format strings, and they're pretty much placeholders for the values that you pass in after the string. `{0}` will get replaced with the first parameter you pass in, `{1}`, will get replaced with the next, `{2}` will get replaced with the next after that, and so on – Sam I am says Reinstate Monica Oct 06 '14 at 20:17
1

If you wanna read from an SQL database and show the data in grid view, I'd recommend you to use an ORM like Entity Framework or maybe Linq to SQL. This makes the whole procedure a lot easier for you. But if you can't, maybe due to requirement, you have to create a model for your table:

public class MyTableModel{
    public int Id {get; set;}
    public String value {get; set;}
}

Now using normal querying :

con.Open();
List<MyTableModel> DataBind = new List<MyTableModel>();
cmd.CommandText = "SELECT Id, value FROM MyTable";
_DataReader = cmd.ExecuteReader();
if(_DataReader.HasRows) {
   while(_DataReader.Read()){
      DataBind.Add(new MyTableModel() {Id = _DataReader.GetInt(0), value =_DataReader.GetString(1) });
   }
}
con.Close();

Now using a GridView (for GUI) :

DatGrid DG = new DataGrid();
DG.Columns.Add("Id");
DG.Columns.Add("value");
DG.ItemSource = DataBind;

Or for Console app using:

foreach(var i in DataBind){
    Console.WriteLine("{0}\t{1}", i.Id, i.value);
}
Transcendent
  • 5,598
  • 4
  • 24
  • 47
  • 1
    I'll have to study the code, so I understand it. I will try to implement it like this – Altaf Oct 06 '14 at 20:22
0

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());
    }
}
Matt Cruikshank
  • 2,932
  • 21
  • 24
  • It works, not sure I really understand the code though, also did not need the Log declaration, nor was it recognized. I assume if I read up on the string class, I should be better able to understand this? – Altaf Oct 07 '14 at 13:39
  • Sorry about the Log declaration, I've removed it. The reason a table is hard to output is because you need to know the maximum width of all of the values in each column. Then when you output each value, you make sure it's padded to have that many characters. So, to do this, I store all of the output into a list.. of lists of strings. (It's a 2-dimensional array of strings.) – Matt Cruikshank Oct 08 '14 at 14:08