Get The Total of Datagridview Row only in Specific Columns (Only with same Column Name)

Viewed 41

I am trying to get the total of the datagridview row using vb.net. I was able to get the total of full row but what I want is to get the total of only for the Columns Named as "AMOUNT".

Actually what I was trying to do is use the Datagridview as data input section which not been link to any data table ones the input is done will save the data. Only thing I want is to get total for Column Name is "AMOUNT"

I was trying to get the result using the below codes but it gives me total of the current tow

For Each ROWSELECT As DataGridViewRow In ReviewGrid.Rows
            If Grid1.Rows.Count > 0 Then
                Dim CTotal As Decimal = 0
                'Dim crow As DataGridViewRow = Grid1.CurrentRow
                For RC = 0 To Grid1.CurrentRow.Cells.Count - 1
                    CTotal += ROWSELECT.Cells(RC).Value

Thanks You!

[1]: https://i.stack.imgur.com/cFP0H.png

1 Answers

If this is from a database query you could just do the math as part of the query. If the columns are dynamic, how are they being fed into the grid? If it is a DataTable you can loop through the rows, and a nested loop for the columns, you can total only the ones where column.columname is "AMOUNT".

I doubt it's a DataTable since you can't reuse column names, anyway here's two ways I would loop through the columns:

       Dim dt As New DataTable
    With dt
        .Columns.Add("Amount", Type.GetType("System.Int32"))
        .Columns.Add("Count", Type.GetType("System.Int32"))
        .Columns.Add("Amount2", Type.GetType("System.Int32"))
        .Columns.Add("Total Amount", Type.GetType("System.Int32"))

        Dim r = .NewRow
        r(0) = 25
        r(1) = 50
        r(2) = 75
        r(3) = 0

        .Rows.Add(r)

        Dim r2 = .NewRow
        r2(0) = 5
        r2(1) = 10
        r2(2) = 15
        r2(3) = 0

        .Rows.Add(r2)
    End With

    Dim dt2 As New DataTable

    dt2 = dt.Copy

    For i = 0 To dt.Rows.Count - 1
        For j = 0 To dt.Columns.Count - 2
            If dt.Columns(j).ColumnName.Contains("Amount") = True Then
                dt.Rows(i)(3) = dt.Rows(i)(j) + dt.Rows(i)(3)
            End If
        Next
    Next

    GridView1.DataSource = dt
    GridView1.DataBind()

    For Each r As DataRow In dt2.Rows
        For Each c As DataColumn In dt2.Columns
            If c.ColumnName.Contains("Amount") = True AndAlso c.ColumnName.Contains("Total Amount") = False Then
                r(3) = r(c.ColumnName) + r(3)
            End If
        Next
    Next

    GridView2.DataSource = dt2
    GridView2.DataBind()

And here is the output:

Grid 1 uses FOR loops, Grid 2 uses For Each

Related