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
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;
}
}