75

I've cobbled together a C# program that takes a .csv file and writes it to a DataTable. Using this program, I can loop through each row of the DataTable and print out the information contained in the row. The console output looks like this:

--- Row ---
Item: 1
Item: 545
Item: 507
Item: 484
Item: 501

I'd like to print the column name beside each value, as well, so that it looks like this:

--- Row ---
Item: 1   Hour
Item: 545 Day1 KW
Item: 507 Day2 KW
Item: 484 Day3 KW
Item: 501 Day4 KW

Can someone look at my code and tell me what I can add so that the column names will print? I am very new to C#, so please forgive me if I've overlooked something.

Here is my code:

// 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?
    }
}
Athafoud
  • 2,898
  • 3
  • 40
  • 58
Kevin
  • 4,798
  • 19
  • 73
  • 120

5 Answers5

128

You need to loop over loadDT.Columns, like this:

foreach (DataColumn column in loadDT.Columns)
{
    Console.Write("Item: ");
    Console.Write(column.ColumnName);
    Console.Write(" ");
    Console.WriteLine(row[column]);
}
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Just so I understand, should this loop over the loadDT.Columns be within the loop for loadDT.Rows? – Kevin Apr 01 '10 at 03:32
  • 1
    @Kevin: yes, your 1st loop is for `.Rows`, 2nd is for `.Columns`, then you can refer to `row[column.ColumnName]` to access each column value in the current row. – Ahmad Mageed Apr 01 '10 at 03:50
  • Lol. I am just curious, maybe someone come to an understanding why using `var` in this example instead of the `DataColumn` does not work? AFAIK it should work due to the semantics of `var` and `foreach`. – hellouworld Feb 18 '20 at 13:45
  • 2
    @hellouworld: Because `DataColumnCollection` doesn't implement `IEnumerable`, so there is no strongly-typed enumerator for `var` to infer the type from. (this class predates the existence of generics) – SLaks Feb 18 '20 at 14:53
  • This example gives me "foreach statement cannot operate on variables of type 'DataTable' because 'DataTable' does not contain a public instance or extension definition for 'GetEnumerator'" Tried creating my DataTable using var and gets the same result? (My probleam was leaving off ".columns"), having just forEach(DataColumn column in LoadDt) – David Mays Feb 28 '22 at 16:33
34
foreach (DataRow row in dt.Rows)
{
    foreach (DataColumn column in dt.Columns)
    {
        ColumnName = column.ColumnName;
        ColumnData = row[column].ToString();
    }
}
Kjartan
  • 18,591
  • 15
  • 71
  • 96
Yakir Manor
  • 4,687
  • 1
  • 32
  • 25
5

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

table.Columns[1].ColumnName

Karan gupta
  • 51
  • 1
  • 2
3

Code for Find the Column Name same as using the 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;
    }
}
slavoo
  • 5,798
  • 64
  • 37
  • 39
2

Print datatable rows with column

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
Sameer Bahad
  • 555
  • 5
  • 4