C# How can i sum a column of a DataTable after change the Rowfilter?

166 views Asked by At

I have a DatagridView, the users apply filters to it (that are stored in Datatable.DefaultView.RowFilter), that means that the number of rows in screen will change, in that case the "TotalCost" variable must change , but it keeps in the same value because i apply "Compute-(sum)" and that method is taking all te Datatable. Any ida of what could i make to solve this problem? Im workin with 32000+ rows, so i want to evade making a for loop if i can.

1

There are 1 answers

4
Meysam Asadi On

Use the CellValidating DataGridView event.

With it you can get the old value and the new value of the cell.

private void myDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
   oldValue = (int)myDataGridView["yourColumn", e.RowIndex].Value;
   //or
   oldValue = (int)myDataGridView[columnIndex, e.RowIndex].Value;
   //or
   oldValue = (int)myDataGridView[e.ColumnIndex, e.RowIndex].Value;
   newValue = (int)e.FormattedValue;

            
   totalCost = totalCost - oldValue;
   totalCost = totalCost + newValue;
}

Use the RowsAdded event when the user adds a row

private void myDataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    newValue =(int)myDataGridView["yourColumn", e.RowIndex].Value;
    totalCost = totalCost + newValue;
}

Use the UserDeletingRow event when the user deleted a row

private void myDataGridView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
    oldValue = (int)myDataGridView["yourColumn", e.Row.Index].Value;
    totalCost = totalCost - oldValue;
}