Search code examples
sqlvb.netfunctionvalidationdatagrid

Validate datagrid cell comparing with the sum of another cell and a function


I have a datagrid for which I want to check, when I input the value in cell of the DataGridView1.Columns(6), if the cell value of DataGridView1.Columns(7) is bigger than cell value for DataGridView1.Columns(6) plus the result of a function which has the argument as DataGridView1.Columns(1) and gets the total of previous inserted values from DataGridView1.Columns(6).

What I don't know:

  • where to make this check and how to do it?
  • how to assign the argument of the function in the checking formula for each row of the datagrid?

The function is:

Public Shared Function getproddeclarata(ByVal nrfpo As String) As Integer
    Dim total As Integer
    Dim con As New SqlConnection
    Try
        con = New SqlConnection("Data Source=SVNAV;Initial Catalog=NAV_Vermorel_Live;User ID=sa;Password=1234")
        Using cmd As SqlCommand = New SqlCommand("SELECT cast(SUM([Productie Declarata]) as Decimal(18,2)) as TotalOreDeclarate FROM [SC Vermorel SRL$ProductieZilnica] WHERE FPO = @nrfpo", con)
            cmd.Parameters.AddWithValue("@nrfpo", nrfpo)
            con.Open()
            total = Convert.ToInt32(cmd.ExecuteScalar())
            con.Close()
        End Using
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    Finally
        If con IsNot Nothing Then
            If con.State = ConnectionState.Open Then                    '
                con.Close()
            End If
            con.Dispose()
        End If
    End Try
    Return total
End Function

Solution

  • For that you can handel the event DataGridView1_CellEndEdit like :

    Private Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
            Try
                Dim rw As DataGridView = DirectCast(sender, DataGridView)
    
              If e.ColumnIndex = 6 Then
                If IsNumeric (rw(e.ColumnIndex, e.RowIndex).Value) andalso rw(e.ColumnIndex, e.RowIndex).Value)>0  Then
                    If rw(7, e.RowIndex).Value > rw(e.ColumnIndex, e.RowIndex).Value + getproddeclarata(rw(1, e.RowIndex).Value.ToString()) Then
    
                        'Same code here
    
                    End If
                End If
            End If
    
            Catch ex As Exception
    
            End Try
    End Sub