how to get sum dynamically of datagridview column in textbox

后端 未结 5 997
时光说笑
时光说笑 2021-01-14 00:00

I want to get the sum of a column of datagridview and show that in textbox. After each entry the sum should be changed dynamically. For that I am using textChanged event of

5条回答
  •  余生分开走
    2021-01-14 00:17

    If you need to take into account the possibility that a user may edit existing values in the grid rows, you can subscribe to the CellEndEdit event.

    Here, I'm checking the column index so you're not recalculating the sum if any other unrelated columns are edited. (I'm also validating the input and setting the value to 0 if, say, someone enters letters.)

    private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 5)
        {
            decimal result;
            if (!Decimal.TryParse(Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value), out result))
                dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
    
            textBox1.Text = dataGridView1.Rows.Cast()
                                         .Sum(x => Convert.ToDecimal(x.Cells[5].Value))
                                         .ToString();
        }
    }
    

    Others may have better solutions... this is just one possibility.

提交回复
热议问题