简体   繁体   中英

Instead of dataGridView in C# windows application, what should I use for console application to display a table from sql server?

Question as above. I was told to use list<> to do so, but I still have no clue about how to do it exactly. I am new to C#.

You could try something like the very simplified example below...

using System;
using System.Data;
using System.Data.SqlClient;

SqlConnection conn = new SqlConnection(***Your Connection String Here***);
conn.Open();

SqlDataAdapter adpt = new SqlDataAdapter("Select ID, Dish, Price From RestaurantMenu", conn);

DataTable dt = new DataTable();
adpt.fill(dt);

conn.Close();

foreach (DataRow dr in dt.Rows){

     console.WriteLine(dr["ID"].ToString() + " | " + dr["Dish"].ToString() + " | " + dr["Price"].ToString());

}

Doing what jradich1234 did is the most practical approach. You fill a dataset with the table data and then just go through it printing each line and then adding a \\n after the last column.

If you really want to use the list<> object (or you have to do it), then the proccess has a little more of work. Basically you have to create the list and then, instead of printing, you add a new item to the list that represents the row... and then you move through the list and do exactly the same jradich1234 did.

It is a good way to practice the use of lists and simple structs, but it is not as efficiend as the previous answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM