Basically, I have a DataTable
as below:
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?
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.
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.
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); //
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With