Click here to Skip to main content
16,012,611 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a datagridview that contains 4 columns Item,Qty,Price,Amount. the user should enter the item name in the first column. i have a table in the database that all the item names are stored. so the inserted name should be checked if its in database or not. if its not in the databse i want the cell to be cleared like a textbox and the focus remain in that cell. the user should be allowed to Continuo until he enters the correct item name... my biggest problem is making that cell to remain focused
so far i have tried this

What I have tried:

Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit

connect()
sql = "Select ProductName from Products where ProductName = '" & Me.DataGridView1.Rows(e.RowIndex).Cells(0).Value.ToString & "' "
objcmd = New SqlCommand(sql, objcon)
OBJDR = objcmd.ExecuteReader
If OBJDR.Read = False Then
'' display this message
MessageBox.Show("Item Name Is not in the Items list", "Item Name Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
"clear the cell '
Me.DataGridView1.Rows(e.RowIndex).Cells(0).Value = ""
DataGridView1.CurrentCell = DataGridView1.Rows(DataGridView1.CurrentCell.RowIndex).Cells(0)
' DataGridView1.BeginEdit(True)
Exit Sub
End If
end sub
Posted
Updated 8-Aug-16 16:32pm

1 solution

try to put your code in cell validating event

VB
Private Sub DataGridView1_CellValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
       With DataGridView1.Rows(e.RowIndex)
           If e.ColumnIndex = 0 Then
               If Not ItemExists(.Cells(e.ColumnIndex).Value) Then
                   MessageBox.Show("Item Name Is not in the Items list", "Item Name Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                   e.Cancel = True
               End If
           End If
       End With
   End Sub

VB.NET
Function ItemExists(ByVal itemname As String) As Boolean
      Dim bResult As Boolean = True

      connect()
      Sql = "Select ProductName from Products where ProductName = '" & itemname & "' "
      objcmd = New SqlCommand(Sql, objcon)
      OBJDR = objcmd.ExecuteReader
      If OBJDR.Read = False Then
          bResult = False
      End If

      Return bResult
  End Function

 
Share this answer
 
Comments
Sharma Hussein 9-Aug-16 3:08am    
No errors, and its working. Thanks for the tip, will remember that for the future. Thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900