在C#中以表格格式显示结果

时间:2014-10-06 20:03:20

标签: c#

我已经编写了这个方法,我希望将其显示为常规表的输出。(例如列名后跟数据)我无法找到任何方法。我也无法操纵WriteLine来实现这一目标。有什么想法吗?

我是编程和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);
    }
}

3 个答案:

答案 0 :(得分:1)

你应该研究几件事:

  • String.PadRightString.PadLeft,允许您添加空格,直到您的字符串为一定长度。

  • format strings,允许您更轻松地格式化字符串。请注意,您可以使用与Console.WriteLine相同的方式使用String.Format

这是一个样本

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);

答案 1 :(得分:1)

如果您想从SQL数据库中读取并在网格视图中显示数据,我建议您使用ORM,如Entity Framework或Linq to SQL。这使整个过程变得更加容易。但是,如果你不能,可能是因为要求,你必须为你的桌子创建一个模型:

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

现在使用正常查询:

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();

现在使用GridView(用于GUI):

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

for Console app 使用:

foreach(var i in DataBind){
    Console.WriteLine("{0}\t{1}", i.Id, i.value);
}

答案 2 :(得分:0)

这样的事可能会奏效:

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());
    }
}