keypress在datagridview上只有字符“abcde”并转换为大写

时间:2016-04-21 12:00:06

标签: vb.net datagridview

如何限制keypress仅限datagridview字符 abcde 并在vb.net上转换为大写?

Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing    
        If DataGridView1.CurrentCell.ColumnIndex = 3 Then
                AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBoxabcde_keyPress
        End If
End Sub

Private Sub TextBoxabcde_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
        If Not Char.IsControl(e.KeyChar) And Not Char.IsLetter(e.KeyChar) And e.KeyChar <> "." Then
                e.Handled = True
        End If
End Sub

3 个答案:

答案 0 :(得分:1)

<强>更新

Private Sub DataGridView1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles DataGridView1.KeyPress
    Dim allLetters As String = "abcde"
    If Not allLetters.Contains(e.KeyChar.ToString.ToLower) Then
        e.KeyChar = ChrW(0)
        e.Handled = True
    End If
End Sub

Private Sub dataGridView1_CellFormatting(sender As Object, e As 
DataGridViewCellFormattingEventArgs)
    If e.Value IsNot Nothing Then
        e.Value = e.Value.ToString().ToUpper()
        e.FormattingApplied = True
    End If
End Sub

答案 1 :(得分:0)

另一个解决方案,我试试这个,它的工作

    Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing    
            If DataGridView1.CurrentCell.ColumnIndex = 3 Then
                    DirectCast(e.Control, TextBox).CharacterCasing = CharacterCasing.Upper
                    AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBoxabcde_keyPress
            End If
    End Sub

    Private Sub TextBoxabcde_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
            If Not (Asc(e.KeyChar) = 8) Then
            Dim allowedChars As String = "ABCDE"
                        If Not allowedChars.Contains(e.KeyChar.ToString.ToUpper) Then
                                 e.Handled = True 
                        End If
            End If
    End Sub

感谢你的帮助Claudius

答案 2 :(得分:0)

试试这个

Dim txtEC As DataGridViewTextBoxEditingControl = Nothing
Private Sub DGV_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DGV.EditingControlShowing

If TypeOf e.Control Is DataGridViewTextBoxEditingControl Then
    If DGV.CurrentCell.ColumnIndex =1  Then
        txtEC = DirectCast(e.Control, DataGridViewTextBoxEditingControl)
        txtEC.CharacterCasing = CharacterCasing.Upper
    End If
End If
End Sub

Private Sub DGV_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DGV.CellEndEdit

If txtEC IsNot Nothing Then
      txtEC.CharacterCasing = CharacterCasing.Normal
      txtEC = Nothing
End If
End Sub