[英]How to show the dataTable in c# console?
I have create a simple program to read from the txt file to load the data to DataTable
. 我已经创建了一个简单的程序,可以从txt文件读取数据并将数据加载到
DataTable
。 But how can I display the DataTable
info in the console? 但是如何在控制台中显示
DataTable
信息? The Console.Write
/ Console.WriteLine
does not accept the DataTable
as a parameter? Console.Write
/ Console.WriteLine
不接受DataTable
作为参数吗?
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CompareLinuxWithWindow
{
class Program
{
static void Main(string[] args)
{
ConvertToDataTable(@"C:\Users\manchunl\Desktop\Sample.txt", 10);
Console.WriteLine();
Console.WriteLine("Press enter to exit.");
Console.Read();
}
public static DataTable ConvertToDataTable(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
for (int col = 0; col < numberOfColumns; col++)
tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));
string[] lines = System.IO.File.ReadAllLines(filePath);
foreach (string line in lines)
{
var cols = line.Split(',');
DataRow dr = tbl.NewRow();
for (int cIndex = 0; cIndex < 10; cIndex++)
{
dr[cIndex] = cols[cIndex];
}
tbl.Rows.Add(dr);
}
return tbl;
}
}
}
You are almost there. 你快到了。 Please try this
请试试这个
using System;
using System.Data;
namespace CompareLinuxWithWindow
{
class Program
{
static void Main(string[] args)
{
DataTable dt= ConvertToDataTable(@"C:\Users\manchunl\Desktop\Sample.txt", 10);
DataTable dt2= ConvertToDataTable(@"C:\Users\manchunl\Desktop\Sample.txt2", 10);
//Add these lines
for(int i=0;i<dt.Rows.Count;i++) //looping through all rows including the column. change `i=1` if need to exclude the columns display
{
for (int j = 0; j < dt.Columns.Count; j++) //looping through all columns
{
Console.WriteLine(dt.Rows[i][j]); //display of the data
}
}
//End of change
//Added for 2nd txt file
for(int i=0;i<dt2.Rows.Count;i++) //looping through all rows including the column. change `i=1` if need to exclude the columns display
{
for (int j = 0; j < dt2.Columns.Count; j++) //looping through all columns
{
Console.WriteLine(dt2.Rows[i][j]); //display of the data
}
}
//End :: Added for 2nd txt file
Console.WriteLine("Press enter to exit.");
Console.Read();
}
public static DataTable ConvertToDataTable(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
for (int col = 0; col < numberOfColumns; col++)
tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));
string[] lines = System.IO.File.ReadAllLines(filePath);
foreach (string line in lines)
{
var cols = line.Split(',');
DataRow dr = tbl.NewRow();
for (int cIndex = 0; cIndex < numberOfColumns; cIndex++)//changed hardcoded value of 10 to numberOfColumns
{
dr[cIndex] = cols[cIndex];
}
tbl.Rows.Add(dr);
}
return tbl;
}
}
}
Kindly let me know if this helps. 请告诉我是否有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.