Convert Code to Class function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mshmyob
    Recognized Expert Contributor
    • Jan 2008
    • 903

    Convert Code to Class function

    I am new to vb.net and would like to be able to convert the following code to it's own function - either inside the current module or better yet in a seperate class.

    This code currently runs in the KEYPRESS event and ensures only numbers, decimal point, 2 decimals etc. are entered and not letters. Works exactly how I want it but would now like it in a function.

    I need this code in numerous text box controls but I would rather just call it somehow with a function.

    Any ideas?

    [code=vb]
    Dim dot As Integer, ch As String

    If Not Char.IsDigit(e. KeyChar) Then e.Handled = True
    If e.KeyChar = "-" And txtStartValue.S electionStart = 0 Then e.Handled = False 'allow negative number
    If e.KeyChar = "." And txtStartValue.T ext.IndexOf("." ) = -1 Then e.Handled = False 'allow single decimal point

    dot = txtStartValue.T ext.IndexOf("." )
    If dot > -1 Then 'allow only 2 decimal places
    ch = txtStartValue.T ext.Substring(d ot + 1)
    If ch.Length > 1 Then e.Handled = True
    End If

    If e.KeyChar = Chr(13) Then GetNextControl( txtStartValue, True).Focus() 'Enter key moves to next control in Tab order
    If e.KeyChar = Chr(8) Then e.Handled = False 'allow Backspace
    [/code]

    cheers,
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    A) Make a custom text box that inherits from TextBox, that uses this method on Keypress event. Now you can just drag this new control onto any form at any time, as many as you want. This would be the more correct way. There is a tutorial that does some of this: Making controls that inherit from other controls.
    Buiding an application - Part 1


    B) In form designer select all of your textboxes as once. Go to the events in Properties pallet. Point *all* of the text boxes' KeyPress event to your one method. It's perfectly legal.

    Comment

    • mshmyob
      Recognized Expert Contributor
      • Jan 2008
      • 903

      #3
      Thank you. That is a neat trick.

      cheers,

      Comment

      • mshmyob
        Recognized Expert Contributor
        • Jan 2008
        • 903

        #4
        I have converted my code to a function. The code can be found here.

        cheers,

        Comment

        Working...