我有一个Datagridview,包含4列Item,Qty,Price,Amount。用户应在第一列中输入项目名称。我在数据库中有一个表,存储了所有项目名称。因此,如果插入的名称在数据库中,则应该检查它。如果它不在数据库中,我希望像TextBox一样清除单元格,焦点仍然在那个单元格中。用户不应该被允许继续,直到他输入正确的项目名称...到目前为止,我已经尝试过这个
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
MessageBox.Show("Item Name Is not in the Items list", "Item Name Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
''clearing the cell '
Me.DataGridView1.Rows(e.RowIndex).Cells(0).Value = ""
'' here i want the cell to get foucus and the cursor remain like textbox
DataGridView1.CurrentCell = DataGridView1.Rows(DataGridView1.CurrentCell.RowIndex).Cells(0)
' DataGridView1.BeginEdit(True)
Exit Sub
End If
End Sub
这是我的datagridview的图像
这是一个datagridview,在用户输入时显示给用户,因此他可以从中选择项目名称。它的工作方式类似于ComboBox AutoComplete。
答案 0 :(得分:0)
最后我得到了我想要的东西。我把代码放在单元格验证事件
中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
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