Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through each element in a DataRow

Tags:

c#

loops

foreach

Basically, I have a DataTable as below:

Enter image description here

I want to run a method per element per row which has the parameters

AddProductPrice(SKU, Price, PriceBracket)

As an example...:

If we take the first row of data, the method will be run a potential of 16 times, once for each time Total Price X isn't null.

So for the first total price in the first row the call will be:

AddProductPrice(SKU, <Total Price 1 value>, 1)

Then for the second total price in the first row the call will be:

AddProductPrice(SKU, <Total Price 2 value>, 2)

Please note: for the National Selling element the call would be:

AddProductPrice(SKU, <National Selling value>, 16)

Is there a clever way to loop through each element in a DataRow to make the procedure more efficient?

like image 978
swade1987 Avatar asked Nov 22 '11 16:11

swade1987


People also ask

What is the method used to return the DataRow?

You use DataTable's NewRow method to return a DataRow object of data table, add values to the data row and add a row to the data Table again by using DataRowCollection's Add method.

How do you initialize a DataRow?

To create a new DataRow, use the NewRow method of the DataTable object. After creating a new DataRow, use the Add method to add the new DataRow to the DataRowCollection. Finally, call the AcceptChanges method of the DataTable object to confirm the addition.


1 Answers

For each row, looping through the columns and then finding the index of "Total Price", "National Selling" and adding product price accordingly.

    for (int i = 0; i < dataTable.Rows.Count; i++)
    {
        DataRow myRow = dataTable.Rows[i];
        for (int j = 0; j < dataTable.Columns.Count; j++)
        {
            if (dataTable.Columns[j].ColumnName.IndexOf("Total Price") > 0)
            {
                AddProductPrice(SKU, myRow.ItemArray[j], j);
            }
            else if (dataTable.Columns[j].ColumnName.IndexOf("National Selling") > 0)
            {
                AddProductPrice(SKU, myRow.ItemArray[j], 16); //
            }
        }
    }
like image 115
Elias Hossain Avatar answered Oct 07 '22 04:10

Elias Hossain