Skip to main content

Problem:

How can you validate numerics in a .Net Winforms TextBox control.

Resolution:

The keypress event in .Net allows you to trap when a key is pressed on the keyboard and interpret what key was pressed. This allows you ensure that only digits , "." , " " and "-" are entered.

More complex checking can also be performed on the TextChanged Event. This is fired when the Text in a textbox is changed and allows you to check the full text that is in the control.

Some examples of using these events to handle numeric checking is:-

       method-id.  "textBox1_KeyPress" final private.

       linkage section.

       01 sender object.

       01 e S-W-Forms-KeyPressEventArgs.

       procedure division using by value  sender e.

       

           set ws-string to e::"KeyChar"

           if cChar::"IsControl"(ws-string , 0)

               exit method

           end-if

           

           if not ( ws-string::"CompareTo"(".") = 0)

               if not ( ws-string::"CompareTo"("-") = 0)

                   if not ( ws-string::"CompareTo"(" ") = 0)

                       if not (cChar::"IsDigit"(ws-string , 0))

                           set e::"Handled" to true

                           invoke cConsole::"Beep"()

                   end-if

               end-if

           end-if

       

       end method "textBox1_KeyPress".

       method-id.  "textBox1_TextChanged" final private.

       01  ls-decimal      decimal.

       linkage section.

       01 sender object.

       01 e System-EventArgs.

       procedure division using by value  sender e.

       

           if not decimal::"TryParse"(textBox1::"Text" , ls-decimal) and not textBox1::"Text"::"Length" = 0

               set textBox1::"BackColor" to cColor::"Red"

           else

               set textBox1::"BackColor" to cSystemColor::"Window"

           end-if  

       

       end method "textBox1_TextChanged".

A working project is attached this this Knowledgebase article.

Attachments:

NumericValidation.zip

Old KB# 1351