0

我正在寻找一种在我的整个 datagridview 中制定全局规则的方法,如果用户输入负数或将其中一个 datagridviewcells 留空,则消息框将告诉用户发生了无效条目。在消息框之后,我希望能够为 datagridviewcell 提供默认值“na”。我的 datagridview 使用 oledataadapter 连接到一个 excel 电子表格。到目前为止,我在 MSDN 上找到了这段代码,但是当我使用它时,我的程序没有正确编译。除了 cellvalidating 事件之外,我还有其他地方可以使用此代码吗?如果没有,我将不胜感激有关此事的任何其他建议或想法。非常感谢!

Private Sub dataGridView1_CellValidating(ByVal sender As Object, _
ByVal e _
As DataGridViewCellValidatingEventArgs) _
Handles dataGridView1.CellValidating

Me.dataGridView1.Rows(e.RowIndex).ErrorText = "" 
Dim newInteger As Integer 


If dataGridView1.Rows(e.RowIndex).IsNewRow Then Return 
If Not Integer.TryParse(e.FormattedValue.ToString(), newInteger) _
    OrElse newInteger < 0 Then

    e.Cancel = True 
    Me.dataGridView1.Rows(e.RowIndex).ErrorText = "the value must be a non-negative integer" 

End If 

结束子

4

1 回答 1

0

您可以在 EditingControlShowing 事件中执行此操作...

Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
    Try
        'remove if there is already a handler
        RemoveHandler e.Control.KeyPress, AddressOf TextNumberKeypress
        'add handler
        AddHandler e.Control.KeyPress, AddressOf TextNumberKeypress

    Catch ex As Exception
        '... 
    End Try
End Sub


Sub TextNumberKeypress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
    Dim k As Byte = Asc(e.KeyChar)
    Dim s As String = "0123456789"

    If Not s.Contains(e.KeyChar) Then
        e.Handled = True        
        If Not (k = 8 Or k = 13 Or k = 1 Or k = 3 Or k = 22) Then e.Handled = True
    End If
End Sub
于 2013-06-24T17:18:07.327 回答