Nick Mackenzie Nick Mackenzie - 11 months ago 46
Vb.net Question

Add/Subtract value to a value of a presiding cell value vb.net

enter image description here

I have a datagridview as one above. I need to get the balance i.e by adding or subtracting the values of Credit or debit to the value of the balance in the presiding row.

Answer Source

1) You can do SUM(xxx) in your database query

2) Client-side - there are many ways, but here is how to sum values in one column and put result into a NumericUpDown.

Dim SumVal1 as int32
For ir = 0 to Me.dgw.rows.count - 1
    Dim dr as DataGridViewRow = me.dgw.rows(ir)
    SumVal1 += dr.Cell("Val1Column").value
next ir
Me.ResultNumericUpDown.Value = SumVal1

However, I'd be very careful about combining bound and unbound data in one DataGridView. If you can, avoid it. Either do data manipulation in query, or do following step after data reading and before you bind data to dataGridView:

Dim ds as new dataSet
ds = DAL.MyDBreadFuncion(cmdText) -- read data from database
Dim dt as new DataTable  -- create new datatable to manipulate data
dt = ds.tables(0)
dt.rows.add()  -- add an empty row

Dim SumVal1 as int32
For ir = 0 to dt.rows.count - 2
    Dim dr as DataRow = dt.rows(ir)
    SumVal1 += dr("Val1Column")
next ir
dt.rows(dt.rows.count -1)("Val1Column") = SumVal1

Me.dgw.datasource = dt
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download