我拼凑了一个C#程序,该程序获取.csv
文件并将其写入DataTable
。使用这个程序,我可以遍历DataTable
的每一行并打印出行中包含的信息。控制台输出如下所示:
--- Row ---
Item: 1
Item: 545
Item: 507
Item: 484
Item: 501
我想在每个值旁边打印列名,以便它看起来像这样:
--- Row ---
Item: 1 Hour
Item: 545 Day1 KW
Item: 507 Day2 KW
Item: 484 Day3 KW
Item: 501 Day4 KW
有人可以查看我的代码并告诉我可以添加的内容以便打印列名称吗?我对C#很新,所以如果我忽视了某些事情,请原谅我。
这是我的代码:
// Write load_forecast data to datatable.
DataTable loadDT = new DataTable();
StreamReader sr = new StreamReader(@"c:\load_forecast.csv");
string[] headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
loadDT.Columns.Add(header); // I've added the column headers here.
}
while (sr.Peek() > 0)
{
DataRow loadDR = loadDT.NewRow();
loadDR.ItemArray = sr.ReadLine().Split(',');
loadDT.Rows.Add(loadDR);
}
foreach (DataRow row in loadDT.Rows)
{
Console.WriteLine("--- Row ---");
foreach (var item in row.ItemArray)
{
Console.Write("Item:");
Console.WriteLine(item); // Can I add something here to also print the column names?
}
}
答案 0 :(得分:97)
您需要循环遍历loadDT.Columns
,如下所示:
foreach (DataColumn column in loadDT.Columns)
{
Console.Write("Item: ");
Console.Write(column.ColumnName);
Console.Write(" ");
Console.WriteLine(row[column]);
}
答案 1 :(得分:22)
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
ColumnName = column.ColumnName;
ColumnData = row[column].ToString();
}
}
答案 2 :(得分:3)
如果您不想遍历所有列,也可以像这样访问列名:
table.Columns [1] .ColumnName
答案 3 :(得分:2)
查找列名的代码与使用sql中的Like
相同。
foreach (DataGridViewColumn column in GrdMarkBook.Columns)
//GrdMarkBook is Data Grid name
{
string HeaderName = column.HeaderText.ToString();
// This line Used for find any Column Have Name With Exam
if (column.HeaderText.ToString().ToUpper().Contains("EXAM"))
{
int CoumnNo = column.Index;
}
}
答案 4 :(得分:0)
使用列
打印数据表行Here is solution
DataTable datatableinfo= new DataTable();
// Fill data table
//datatableinfo=fill by function or get data from database
//Print data table with rows and column
for (int j = 0; j < datatableinfo.Rows.Count; j++)
{
for (int i = 0; i < datatableinfo.Columns.Count; i++)
{
Console.Write(datatableinfo.Columns[i].ColumnName + " ");
Console.WriteLine(datatableinfo.Rows[j].ItemArray[i]+" ");
}
}
Ouput :
ColumnName - row Value
ColumnName - row Value
ColumnName - row Value
ColumnName - row Value