如何在这个 C # 程序中打印列名?

我拼凑了一个 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?
}
}
330449 次浏览

你需要在 loadDT.Columns上循环,像这样:

foreach (DataColumn column in loadDT.Columns)
{
Console.Write("Item: ");
Console.Write(column.ColumnName);
Console.Write(" ");
Console.WriteLine(row[column]);
}
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
ColumnName = column.ColumnName;
ColumnData = row[column].ToString();
}
}

查找列名的代码与在 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;
}
}

用列打印可数据化的行

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

如果不想循环访问所有列,也可以像下面这样访问列名:

Table.Columns [1] . ColumnName