Blaze M - 1 year ago 106

SQL Question

I've been thinking about what is the best way to do my datagridview math. I have this datagridview which I need to go row by row multiplying column "castka" with počet" and then + the next row then + next row until Im on the end and then display the final value in textBox. As I'm beginner in c# and sql I wanted to discuss this with you for first. (codes are welcome :) )

thank you so much.

This is how my table looks like.

Would someone recommend me something please?

`void calculateProductTwoColumns(int castkaIndex, int pocetIndex)`

{

double[] outVals = new double[tot_rows + 1]; //Array including product of both columns per row

int curRow = 0;

foreach (DataGridViewRow row in dtg_ksluzby.Rows)

{

curRow = curRow + 1;

outVals[curRow] = (double)row.Cells[4].Value * (double)row.Cells[6].Value;

// MessageBox.Show(""+ outVals.ToString());

kpriplac.Text = outVals.ToString();

}

}

this is how I call it on form_load

`calculateProductTwoColumns( 4, 6);`

Answer

`DataGridView`

is a control for data-displaying purposes; if you want to perform any kind of mathematical operation you would have to create an algorithm to retrieve the data and carry out the calculations. If you are getting the data from a DB, it would be quicker to perform the operations by relying on queries. Iterating through the cells is not too difficult, neither writing to a `TextBox`

; here you have a sample function performing both actions (between `dataGridView1`

and `textBox1`

):

```
private void calculateSumColumn(int curColumn)
{
double valueCurColumn = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
valueCurColumn = valueCurColumn + (double)row.Cells[curColumn].Value;
}
textBox1.Text = valueCurColumn.ToString();
}
```

Applied to your specific case:

```
private void calculateProductTwoColumns(int castkaIndex, int pocetIndex, int tot_rows)
{
double[] outVals = new double[tot_rows + 1]; //Array including product of both columns per row
int curRow = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
curRow = curRow + 1;
outVals[curRow] = (double)row.Cells[castkaIndex].Value * (double)row.Cells[pocetIndex].Value;
}
}
```