Search code examples
c#wpfdatasetwpfdatagridcalculated-columns

How to calculate totals of wpf datagrid column with dataset


I am trying to figure out what is the best way to calculate a total value of DataGrid column in wpf.

  • I´m using dataset to display data from sql in my DataGrid( and tableApapter for update)
  • I want the info to update dynamically when I edit numbers in the DataGrid
  • I want the total sum to display in label/textbox or footer below the DataGrid

What is the best practice to do this ?


Solution

  • You can listen on various events that will cause a value in the column to change, and then compute the total whenever the event is fired by calling a method like "calculateTotal()" below.

    DataTables events are defined here: here

    private int colTotal = 0; // class level
    
    public Myclass()
    { 
        // Add a ColumnChanged event handler for the table.
        MyDataTable.ColumnChanged += new DataColumnChangeEventHandler(Column_Changed);
        // wire up more event handlers here..
    }
    
    private static void Column_Changed(object sender, DataColumnChangeEventArgs e )
    {
       calculateTotal();
    }
    
    // calculate total of specified column
    void calculateTotal()
    {
       colTotal = myDataSet.Tables["myTable"].Compute("SUM(myColumnName)", String.Empty);
    } 
    

    colTotal will be a public property that is bound to your textbox or label

    public int ColTotal
    {
        get 
        { 
          return colTotal; 
        }
        set
        {
          colTotal= value;
          OnPropertyChanged("ColTotal");
        }
    }