Currently I have code which looks up a database table through a SQL connection and inserts the top five rows into a Datatable (Table).
using(SqlCommand _cmd = new SqlCommand(queryStatement, _con)) { DataTable Table = new DataTable("TestTable"); SqlDataAdapter _dap = new SqlDataAdapter(_cmd); _con.Open(); _dap.Fill(Table); _con.Close(); }
How do I then print the contents of this table to the console for the user to see?
After digging around, is it possible that I should bind the contents to a list view, or is there a way to print them directly? I'm not concerned with design at this stage, just the data.
Any pointers would be great, thanks!
SqlConnection con = new SqlConnection(constr); con. Open(); SqlCommand cmd = new SqlCommand("select * from info", con); SqlDataAdapter ad = new SqlDataAdapter(cmd); DataSet dt = new DataSet(); ad. Fill(dt); Console. WriteLine(dt.
Printing Data Sets with the PRINTDS Command. Use the PRINTDS command to: Print a sequential data set, one member of a partitioned data set, or an entire partitioned data set including the directory (DATASET operand) Print only the members or only the directory of a partitioned data set (MEMBERS, DIRECTORY operands)
In the ADO.NET library, C# DataTable is a central object. It represents the database tables that provide a collection of rows and columns in grid form. There are different ways to create rows and columns in the DataTable.
you can try this code :
foreach(DataRow dataRow in Table.Rows) { foreach(var item in dataRow.ItemArray) { Console.WriteLine(item); } }
Update 1
DataTable Table = new DataTable("TestTable"); using(SqlCommand _cmd = new SqlCommand(queryStatement, _con)) { SqlDataAdapter _dap = new SqlDataAdapter(_cmd); _con.Open(); _dap.Fill(Table); _con.Close(); } Console.WriteLine(Table.Rows.Count); foreach(DataRow dataRow in Table.Rows) { foreach(var item in dataRow.ItemArray) { Console.WriteLine(item); } }
Here is another solution which dumps the table to a comma separated string:
using System.Data; public static string DumpDataTable(DataTable table) { string data = string.Empty; StringBuilder sb = new StringBuilder(); if (null != table && null != table.Rows) { foreach (DataRow dataRow in table.Rows) { foreach (var item in dataRow.ItemArray) { sb.Append(item); sb.Append(','); } sb.AppendLine(); } data = sb.ToString(); } return data; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With