Search code examples
vb.netmodulekeypress

How to call a Sub Statement that contains keypress validations from a Module to Windows form?


I have this Sub Statement on my Module that contains character restriction from a keypress event.

  Public Sub keyFilter(ByRef e As System.Windows.Forms.KeyPressEventArgs)
          If Not ((Asc(e.KeyChar) >= 48 And Asc(e.KeyChar) <= 57) Or
            (Asc(e.KeyChar) >= 65 And Asc(e.KeyChar) <= 90) Or
            (Asc(e.KeyChar) >= 97 And Asc(e.KeyChar) <= 122) Or
            Asc(e.KeyChar) = 8 Or
            Asc(e.KeyChar) = 127 Or
            Asc(e.KeyChar) = 95 Or
            Asc(e.KeyChar) = 32) Then
                e.KeyChar = ChrW(0)
                e.Handled = False
          End If
End Sub 

I want to call the Sub statement above to windows form keypress event by using this code but this produces an error. It says ,Value of type 'Char' cannot be converted to 'System.Windows.Forms.KeyPressEventArgs

Private Sub txtTableName_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtTableName.KeyPress

    Call keyFilter(e.KeyChar)

End Sub

Can you tell me what is/are the problem with my codes? Is it really possible to call a keypress event function in windows form? Thanks.


Solution

  • Try to change this line :

    Call keyFilter(e.KeyChar)
    

    to this :

    Call keyFilter(e)
    

    KeyFilter expect KeyPressEventArgs as parameter, but you passed e.KeyChar which is a Char. You should pass e which is KeyPressEventArgs instead.