Text Box Validation help...

SSP_TY

New member
Joined
Mar 29, 2006
Messages
2
Programming Experience
Beginner
Alright here's the deal, I have numerous text boxes on a form and I want to be able for the user only to be able to enter integers or decimal numbers within the text boxes. Right now this is the current code I have in order for them to only be able to enter integers but I want to be able integers and decimals if needed, how can I adapt this code in order for this to happen?

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

If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
e.Handled = True
End If

End Sub
 
If you're going to use that code then you'd need to test whther the character is a decimal point as well, then you'd also need to check whether there is already a deciaml point present, then you'd also need to check whether the current deciaml point was selected and would thus be overwritten by the new decimal point. You might also want to consider negative numbers. None of this prevents the user pasting invalid text from the clipboard either. Creating a TextBox that will validate numbers and prevents any circumvention of that validation is not trivial. If it is just the end that is important then I'd suggest using the NumberBox from the WFC library in my signature. If the means to that end are also important, either for homework or your own interest, then you'll need to implement what I said first up. You'll need to use the String.IndexOf method to determine if a deciaml point is present. You'll also need to use the SelectionStart and SelectionLength properties of the TextBox to determine what part of the Text is selected. If a deciaml point is present and some text is selected you need to check whether the existing decimal point is in that selected text, because if it is it will be replaced by the new deciaml point so the key press should be allowed.
 
Alright, I think I understand what you're saying and yes it is the end input results for which is important, so how would I go about using that link in your sig? I see the number box on the screen, but what do I do from there? Do you supply code for it or what do you mean when you are referring me to it?
 
You go to their download page and download it, then install it. Once you've done that you can add the controls and components it contains to the Toolbox in VS.NET. Once you've done that you can add them to your forms just like the standard .NET controls.
 
Back
Top