Auto Sum Cells that are Currently Selected

tommyready

Member
Joined
Jul 1, 2009
Messages
23
Programming Experience
3-5
I was wondering if there was a way to auto sum cells that are selected in a datagrid. The same feature that is in Excel. So If i drag a few cells that hold integers I can total them up for display somewhere. Any help would be great!
 
Here's some C# that I use to do this:

VB.NET:
    private void _ibaDgv_SelectionChanged(object sender, EventArgs e)
    {
      decimal sumOf = 0, tmpD = 0;
      int countOf = 0;
      foreach (DataGridViewCell c in _ibaDgv.SelectedCells) {
        if (decimal.TryParse(c.Value.ToString(), out tmpD))
          sumOf += tmpD;

        countOf++;

      }
      _sumSelLbl.Text = "Sum of selected: " + sumOf;
      _countSelLbl.Text = "Count of selected: " + countOf;
    }

You may use a converter, or translate it manually by reading it.. The following is a vb.net version using the developerfusion converter but I do not guarantee that it compiles or works:

VB.NET:
    Private Sub _ibaDgv_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs) 
    Dim sumOf As Decimal = 0, tmpD As Decimal = 0 
    Dim countOf As Integer = 0 
    For Each c As DataGridViewCell In _ibaDgv.SelectedCells 
        If Decimal.TryParse(c.Value.ToString(), tmpD) Then 
            sumOf += tmpD 
        End If 
        
            
        countOf += 1 
    Next 
    _sumSelLbl.Text = "Sum of selected: " & sumOf 
    _countSelLbl.Text = "Count of selected: " & countOf 
End Sub
 
Back
Top