Jeff Bootsholz
Jeff Bootsholz

Reputation: 3068

C# for loop changing format DataTable

Below is my current format for exporting the results of Datatable and write into the excel

Would you please How can I change the foreach into forloop and check the name of the Data Column ?

For instance, I have got a data Table as selecting all details from customers , such as ID, name , product , price

I wan to access of the current position of looping data column is on the product or not

            foreach (DataRow r in table.Rows)
            {
                currentCol = 1;
                foreach (DataColumn c in table.Columns)
                {
                    excelDoc.setCell(1, 1, currentRow, currentCol, r[currentCol - 1].ToString());
                    currentCol++;
                }
                currentRow++;
            }

Upvotes: 0

Views: 721

Answers (1)

tsukimi
tsukimi

Reputation: 1645

Something like:

 DataRow row;
    for(int currentRow=0; currentRow < table.Rows.Count; currentRow++)
    {
         row = table.Rows[currentRow];

            for (int currentCol = 0; currentCol < table.Columns.Count; currentCol++ )
            {
                if (table.Columns[currentCol].ColumnName == "product")
                {
                    excelDoc.setCell(1, 1, currentRow, currentCol, row[currentCol - 1].ToString());
                }

            }


    }

Upvotes: 1

Related Questions