71

我拼凑了一个 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?
    }
}
4

5 回答 5

119

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

foreach (DataColumn column in loadDT.Columns)
{
    Console.Write("Item: ");
    Console.Write(column.ColumnName);
    Console.Write(" ");
    Console.WriteLine(row[column]);
}
于 2010-04-01T03:16:24.290 回答
30
foreach (DataRow row in dt.Rows)
{
    foreach (DataColumn column in dt.Columns)
    {
        ColumnName = column.ColumnName;
        ColumnData = row[column].ToString();
    }
}
于 2012-07-30T11:55:40.157 回答
5

You can access column name specifically like this too if you don't want to loop through all columns:

table.Columns[1].ColumnName

于 2018-06-14T09:31:24.547 回答
3

Like查找列名的代码与使用in sql的代码相同。

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;
    }
}
于 2014-12-17T11:27:09.393 回答
2

打印带列的数据表行

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
于 2018-04-24T10:46:25.777 回答