如何在Visual Basic中的datagridview中添加d​​atetimepicker?

时间:2016-04-01 06:00:24

标签: vb.net datagridview

我有一个datagridview(DataGridViewsalarydetail)。它有3列:

  1. 公式(仅接受数字和字母),
  2. 生效日期(仅接受日期:2016年9月14日),
  3. 基本费率(仅接受数字和点[。]为双倍)。
  4. 问题是如何将日期时间选择器放在数据网格视图中或如何将日期列设置为仅接受有效日期?

    我使用Visual Basic Express 2015,MySQL,phpMyAdmin和VB.NET

    我尝试过MSDN网站上的代码,但我不知道如何在我的项目中实现。

    Private Sub DataGridViewsalarydetail_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridViewsalarydetail.EditingControlShowing
            If TypeOf e.Control Is TextBox Then
                DirectCast(e.Control, TextBox).CharacterCasing = CharacterCasing.Upper
        End If
    
        If DataGridViewsalarydetail.CurrentCell.ColumnIndex = 0 Then
    
            AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
    
        ElseIf DataGridViewsalarydetail.CurrentCell.ColumnIndex = 1 Then
    
            AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress2
    
        ElseIf DataGridViewsalarydetail.CurrentCell.ColumnIndex = 2 Then
    
            AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress1
    
        End If
    
    End Sub
    
    Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
    
        'If Char.IsDigit(CChar(CStr(e.KeyChar))) = False Then e.Handled = True
    
    End Sub
    
    Private Sub TextBox_keyPress1(ByVal sender As Object, ByVal e As KeyPressEventArgs)
    
        'If Not (Char.IsDigit(CChar(CStr(e.KeyChar))) Or e.KeyChar = ".") Then e.Handled = True
        e.Handled = True
        If e.KeyChar Like "." Or e.KeyChar = Chr(&H8) Or IsNumeric(e.KeyChar) Then
            e.Handled = False
        End If
    
    End Sub
    Private Sub TextBox_keyPress2(ByVal sender As Object, ByVal e As KeyPressEventArgs)
    
        If Not (Char.IsDigit(CChar(CStr(e.KeyChar))) Or e.KeyChar = "/") Then e.Handled = True
        'e.Handled = True
        'If e.KeyChar Like "." Or e.KeyChar Like "/" Or e.KeyChar = Chr(&H8) Or IsNumeric(e.KeyChar) Then
        '    e.Handled = False
        'End If
    
    End Sub
    
    Private Sub DataGridViewsalarydetail_CellValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handles DataGridViewsalarydetail.CellValidating
        If e.ColumnIndex = 1 Then
            Dim dt As DateTime
            If e.FormattedValue.ToString <> String.Empty AndAlso Not DateTime.TryParse(e.FormattedValue.ToString, dt) Then
                MessageBox.Show("Enter correct Date")
                'Me.DataGridViewsalarydetail.Rows(e.RowIndex).ErrorText = "Enter a valid Date time"
                e.Cancel = True
            End If
        End If
    End Sub
    

1 个答案:

答案 0 :(得分:0)

尝试使用datagridview.CellEndEdit event检查用户输入是否正确。

您可以像我在下面的示例中所做的那样使用IsDate function,或者您可以创建自己的函数来验证用户输入。

Set rsRR = DataDB.OpenRecordset("Railroads", dbOpenTable)