views:

419

answers:

1

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 data table 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?
            }
        }
+1  A: 

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
Awesome! Thanks so much for the quick response!
Kevin
Just so I understand, should this loop over the loadDT.Columns be within the loop for loadDT.Rows?
Kevin
@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
Thanks, Ahmad! I greatly appreciate it!
Kevin