Sharma Hussein Sharma Hussein - 1 year ago 126 Question

Datagridview CellValidating is Not working perfectly

I have 3 columns

  • Item Name

  • Quantity on Hand

  • Quantity to transfer

the item name and the qty on hand is diplayed to the user
. If he tries to input a number which is more than the Qty he has on Hand; i need a messageBox to pop up...

this what i have tried

Private Sub DataGridView1_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating

With DataGridView1.Rows(e.RowIndex)
If e.ColumnIndex = 2 Then '' this is the col index for qty to be transfered
If .Cells(2).Value > .Cells(1).Value Then
MessageBox.Show("You don't Have sufficient quantity ", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
e.Cancel = True
End If
End If
End With
end sub

However the event is not firing the exact time I want. It allows me to leave the row without the message popping up.

Answer Source

The value isn't written to the cell yet, so use the value that is being passed to you from the event:

If Convert.ToInt32(e.FormattedValue) > Convert.ToInt32(.Cells(1).Value) Then

Side note: Set Option Strict On in your code since Value and FormattedValue return objects.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download