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

StackOverflow https://stackoverflow.com/questions/21251504

  •  30-09-2022
  •  | 
  •  

Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

KeyFilter() function takes an argument of type KeyPressEventArgs, you should replace the calling statement with Call keyFilter(e), do not pass e.KeyChar..

Try this...

Public Sub keyFilter(ByVal sender As Object, ByVal 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 

Private Sub txtTableName_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtTableName.KeyPress
    Call keyFilter(sender, e)
End Sub
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top