0

我正在尝试找到一种方法来防止用户在提供错误输入时退出 datagridviewcell。对于有问题的 datagridview 列,我想防止用户输入负数,包括零和空白字段。现在我可以阻止这个输入,并显示一条适当的消息,但我不知道如何阻止用户表单在显示消息后退出单元格。我的代码如下所示。如果有人对此问题有任何建议或答案,我将非常感谢您提供的任何帮助。

 Private Sub DataGridView1_CellValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
    If (e.ColumnIndex = 2) Then
        Dim cellData = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
        If cellData Is Nothing OrElse IsDBNull(cellData) OrElse cellData.ToString = String.Empty Then
            MessageBox.Show("Cannot Be Empty")
            e.Cancel = True
        ElseIf cellData <= 0 Then
            MessageBox.Show("Negative Numbers and Zero Not Allowed")
            e.Cancel = True
            Exit Sub



        End If

    End If
End Sub
4

3 回答 3

1

试试这个方法。。

Private Sub DataGridView1_CellValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating    

    If (e.ColumnIndex = 2) Then
        Dim cellData = e.FormattedValue 

        If cellData Is Nothing OrElse IsDBNull(cellData) OrElse cellData.ToString = String.Empty Then
            MessageBox.Show("Cannot Be Empty")
            e.Cancel = True
        Else
            If val(cellData) <= 0 Then
               MessageBox.Show("Negative Numbers and Zero Not Allowed")
               e.Cancel = True
               Exit Sub
            Endif    

        End If

    End If
End Sub
于 2013-07-02T00:47:18.803 回答
1

又是你 ;-) 尝试使用SendKeys和使用CellEndEdit事件。这不是完美的解决方案,但至少它可以完成工作(希望如此)。请参见下面的代码:

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

    If (e.ColumnIndex = 0) Then 'checking value for column 1 only
        Dim cellValue As Integer
        If (Int32.TryParse(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value, cellValue)) Then
            If cellValue < 0 Then
                MessageBox.Show("Negative Numbers Not Allowed") 'This prevents negative numbers
                SendKeys.Send("+{Tab}")
            End If
        Else
            Dim testValue As String = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
            If (String.IsNullOrEmpty(testValue)) Then
                MessageBox.Show("Name Cannot Be Empty")
                SendKeys.Send("+{Tab}")
            End If
        End If

    End If


End Sub
于 2013-07-02T01:38:13.367 回答
0

使用DataGridView.CellValidating事件,并设置:http e.Cancel = true: //msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvalidating.aspx

于 2013-07-01T19:16:13.280 回答