Hi,
I select S.No, name and mark from sql database table. This table contain n number of rows. I want to add(+)/Plus the mark and display in the (n+1) row of datagridview how can i do this.
Thank You

Dani AI

Generated

asked how to show the sum of the mark column as an (n+1)th row in a DataGridView. 's idea to iterate rows is valid for unbound grids; pointed to a related DaniWeb example. Two practical, safe patterns are below (one server-side, one client-side), plus a few cautions about binding and formats.

A. Compute on the server or with DataTable.Compute and append a display-only row (recommended for large sets or when accuracy/performance matters)

' Assume dt is the DataTable bound to the DataGridView
Dim total As Decimal = 0D
Dim obj = dt.Compute("SUM(mark)", String.Empty)
If Not Convert.IsDBNull(obj) Then total = Convert.ToDecimal(obj)

Dim totalRow As DataRow = dt.NewRow()
totalRow("S.No") = DBNull.Value
totalRow("name") = "Total"
totalRow("mark") = total
dt.Rows.Add(totalRow)

' Prevent this display row from being treated as a user change to persist:
totalRow.AcceptChanges()

Notes: SELECT SUM(mark) FROM Table on SQL Server is even faster for big tables. If the grid is bound, add the row to the DataTable (not the DataGridView.Rows collection) and call AcceptChanges() on that DataRow so a later DataAdapter.Update() won’t try to write the total back to the database.

B. Iterate the DataGridView rows (works well for unbound grids)

Dim total As Decimal = 0D
For Each r As DataGridViewRow In dataGridView.Rows
    If Not r.IsNewRow Then
        Dim s = If(r.Cells("mark").Value, "").ToString().Trim()
        Dim n As Decimal
        If s = "-" Then
            n = 0D      ' treat a single dash as a placeholder (adjust if dash means negative)
        Else
            Decimal.TryParse(s, n)
        End If
        total += n
    End If
Next
dataGridView.Rows.Add(Nothing, "Total", total)

Cautions and tips: ensure AllowUserToAddRows = False when summing rows; handle DBNull and localization when parsing; prefer Decimal for money/precise totals; if the extra row should never be saved, show the total in a separate label/status strip or append it to a cloned DataTable used only for display.

Recommended Answers

All 2 Replies

So each row is (n + (n-1)), building on top of itself right? Couldn't you just for loop through each row in the table and just take the current row's value and add it to the lasts (you would of course then need an extra column).

You could check the mark to see if it's '-', then times then multiple the value for the nth row by -1, and then add it.

This snippet (to be found here on DaniWeb) is perhaps not exactly what you want, but you surely can get some ideas out of it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.