[RESOLVED] Perform calculation after user input on DataGridView
Hi guys :wave:
I have DataTable, and is bound to DataGridView. So, when the user inputs some values in 4 columns, it would calculate the sum and put it in the last 2nd last column.
Here's the code that I'm experimenting:
vb.net Code:
Private Sub DataGridView1_RowLeave(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.RowLeave
Dim i As Integer
Dim intTotal As Integer = 0
For i = 5 To DataGridView1.Columns.Count - 3
If Not DataGridView1.Item(e.RowIndex, i).FormattedValue = Nothing Then intTotal += Integer.Parse(DataGridView1.Item(e.RowIndex, i).FormattedValue.ToString)
Next
dt.Rows(e.RowIndex).Item("Total") = intTotal
'DataGridView1.Item(e.RowIndex, DataGridView1.Columns.Count - 2).FormattedValue = intTotal
'MessageBox.Show(e.RowIndex)
End Sub
But when the form is loaded, it would give an error saying out of bounds.
So, basically it should sum up certain columns when the user enters numbers into it and then display it in the last column.
I think, there would be a better way to do this. If you have some suggestions, let me know.
Thanks :wave:
Re: Perform calculation after user input on DataGridView
How about using "CellendEdit" instead, heres one I use
Code:
Private Sub LOT_CHRGDataGridView_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles LOT_CHRGDataGridView.CellEndEdit
If e.ColumnIndex = 1 Then
Me.LOT_CHRGDataGridView.CurrentRow.Cells("tot_amount").Value = CLng(Me.LOT_CHRGDataGridView.CurrentRow.Cells("lbs").Value) / _
CDbl(Me.LOT_CHRGDataGridView.CurrentRow.Cells("divide_by").Value) * CDbl(Me.LOT_CHRGDataGridView.CurrentRow.Cells("amount").Value)
End If
End Sub
Re: Perform calculation after user input on DataGridView
The problem is to do with the way you are going through the loop. you are trying to access something that does not exist.
you need to find out where the error is coming from.... and see how many elements are in the array, and what you are currently trying to read.
Re: Perform calculation after user input on DataGridView
Thanks guys :wave:
It was my mistake. I used RowIndex in place of ColumnIndex and vice versa(in my code). :D
I have changed it and added the code in CellEndEdit event. :)