In general, there’s a various way
how to sum the total in DataGridView. In fact, they use different approach but
the results generate the same output. It depend the programmer or developer how
they are going to use. In this example, I used databinding approach to sum the
total in DataGridView using for loop
statement in Visual Basic.Net (VB.NET). Also you may apply this in any Visual
Studio Languages such as C#, ASP.Net, WPF, and etc. as long the DataGridView
available in toolbox. However, the source code I provided here not necessarily
the same when you apply to other languages. In addition, make some modification
if you are going to use to other languages. Here is the sample source code to
sum the total in DataGridView using VB.NET.
For i = 0 To
Me.TblStudentPaymentDataGridView.RowCount - 1
sum += Me.TblStudentPaymentDataGridView.Rows(i).Cells(0).Value.ToString()
Me.TblStudentPaymentBindingSource.Current.item("TotalPaid") = sum
Next
If you quite familiar
in databinding approach, I think it’s difficult to understand what does code
stand for and what output will be generated.
Me.TblStudentPaymentDataGridView.RowCount, a code
generated when you drag a certain field from your datasource and all other
namespaces that could be use.
RowCount
– 1 means all rows will be read but we don’t yet specify which column
in rows we are going to sum in DataGridView. To specify the column and sum the
total rows, we use Me.TblStudentPaymentDataGridView.Rows(i).Cells(0).Value.ToString().
Don’t forget to use + operator to sum
the total rows in DataGridView.
Rows(i) to count all rows in the DataGridView,
Cells(0) determine
which column field name to sum. Why is it in Cell 0? Consider an array start at index 0, the same in
DataGridView or Table in Database, it start from index 0. So, if the column you
want to sum the total, use a number index to specify the field name of your
DataGrid column and let RowCount sum whatever the number is in your rows.
The total sum we made in DataGridView
will be store in Me.TblStudentPaymentBindingSource.Current.item("TotalPaid") = sum. TotalPaid is the name of a column name in
DataGrid where our total sum will be store.
0 comments:
Post a Comment