VB如何使DataGridView在验证失败(CellEndEdit)时保持在同一单元格

3

你好,我刚开始接触编程。上个月做了一个有用的程序,现在转而做一些稍微大一点的事情——数据网格视图让我头痛。我的Datagridview没有绑定到数据库。简单地说,我有两个不同窗体上的DataGridviews——一个本质上是一个字典(Dictionary),另一个是数据输入表格(有点像Excel)。数据输入 Datagrid 与字典 Datagrid 相互交叉参照。我已经解决了这个问题,但是我需要做的是——如果编辑后的数据单元格不在字典中,则不能移动到另一个单元格(即被卡在该单元格中,直到添加正确的字典值为止)。我目前可以让它显示消息框“不在字典中”,但是我的代码不允许移出该单元格的功能不起作用。

以下是代码:

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


    Dim Row As Integer = DataGridView1.CurrentRow.Index
    Dim temp As Integer = 0

    Try
        For i As Integer = 0 To FormGeoDicLith.DataGridViewDicLith.RowCount - 1

'this code references a column in the datagrid dictionary to see if the correct value has been added to the data entry datagrid

            If DataGridView1.Rows(Row).Cells(2).Value = FormGeoDicLith.DataGridViewDicLith.Rows(i).Cells(1).Value Then
                MsgBox("Item found")
                temp = 1
            End If
        Next

        If temp = 0 Then

'this is the problem area
            DataGridView1.Rows(Row).Cells(2).Selected = True

            MsgBox("Code Not In Dictionary")

            Exit Sub

        End If
    Catch ex As Exception

    End Try
End Sub  

问题是DataGridView1.Rows(Row).Cells(2).Selected = True,尽管它看起来选择了单元格,但它只是取消选择,我不能像想要的那样一直停留在单元格中,直到输入正确的字典项。非常感谢您的帮助。

我会调查在 CellEndEdit 之后被调用的事件是什么。其中一个可能会阻止你想要的行为。 - Luminous
同意,但事件不是由我调用的,而是由DatagridView默认行为调用的。 - BAS
没错,但是你总可以添加它们的事件处理方法并加入一个println语句,看看在dgv运行时哪些被引发了。 - Luminous
2个回答

2
您可以使用 DataGridView.CellValidating 事件,该事件在单元格失去输入焦点时发生,从而实现内容验证。

例如:
Private Sub DataGridView1_CellValidating(sender As Object, e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) _
    Handles DataGridView1.CellValidating

    If e.FormattedValue < 0 Or e.FormattedValue > 20 Then
        MsgBox("Please specify a valid value between 0 and 20.")
        e.Cancel = True
    End If

End Sub

您可以通过 e.ColumnIndex 来验证特定列过滤。


单元格验证事件对我的代码造成了很大的麻烦 - 我在“endedit”之前尝试过它。 - BAS
结束编辑对于除了禁止退出单元格之外的所有操作都有效-我尝试了按键和按下事件(我的最初想法是实时验证并在正确输入后创建自动单元格移动-但这也导致了各种意想不到的后果。 - BAS
如果在特定过程(例如:第一次填充DataGridView时)中出现CellValidating问题,请尝试使用AddHandler和RemoveHandler动态添加/删除此事件(链接:https://msdn.microsoft.com/en-us/library/6yyk8z93%28v=vs.90%29.aspx)。 - tezzo
我最终选择了Telerik Radgrid,并使用单元格验证事件。这样做会减少很多麻烦。 - BAS

0

我在编程方面有一些进展-

DataGridView1.CurrentCell = DataGridView1.Rows(Row).Cells(2)

            MsgBox("Code Not In Dictionary")

            DataGridView1.BeginEdit(True)

begin edit函数虽然可以将我拉回到单元格,但下一个单元格被选中后,它会被拉回到正确的单元格并进入编辑模式。在Msgbox之后需要按两次Enter键,如果我不断输入错误的值,则似乎会失败/由于某种原因无法选择单元格。


实际上,它返回到单元格,然后你认为你正在编辑该单元格,但它奇怪地决定将值放在旁边的单元格中(非常奇怪)。 - BAS
我最终放弃了原本的股票DatagridView,转向使用Telerik Radgrid。通过这样做,我成功地摆脱了上述所有问题(虽然有些曲折,但比使用Datagridview时要少得多)。 - BAS

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接