I have a DGV that would change in columns, how would i modify the code to dynamically add all the cells what are present in the row, instead of hardcoding each cell - i could see a problem if i added 31 cells and then a month with 28 would throw an error. I'd miss the first column becuase thats a name, but all the rest are numbers.
For Each SelectedRow as DataGridViewRow in dgv_service_centers.SelectedRows()
Total = SelectedRow.Cells(1).value + SelectedRow.Cells(2).value + SelectedRow Cells(3).value
Next
Cheers, Pete
LINQ is your friend in this case.
Dim sum = dgv_service_centers.SelectedRows.
Cast(Of DataGridViewRow)().
Sum(Function(row) row.Cells.
Cast(Of DataGridViewCell)().
Sum(Function(cell) CInt(cell.Value)))
The inner expression sums the Integer
values from each cell in the current row and the outer expression sums all those sums for the selected rows. If the values are some type other than Integer
, replace the Cint
as appropriate.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.