Math operation with dataGridView columns row by row then display final value in textBox

前端 未结 1 1100
旧巷少年郎
旧巷少年郎 2021-01-24 09:11

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

相关标签:
1条回答
  • 2021-01-24 09:48

    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;
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题