To accomplish what you're asking by modifying your code you could try:
[color=Blue]Private Sub[/color] TextBox1_KeyPress([color=Blue]ByVal[/color] sender [color=Blue]As Object[/color], [color=Blue]ByVal[/color] e As System.Windows.Forms.KeyPressEventArgs) [color=Blue]Handles[/color] TextBox1.KeyPress
[color=Blue] If Me[/color].TextBox1.SelectionStart = 0 [color=Blue]Then[/color]
e.Handled = e.KeyChar = "0"c [color=Blue]OrElse[/color] ([color=Blue]Not[/color] [color=Blue]Char[/color].IsDigit(e.KeyChar) [color=Blue]AndAlso[/color] e.KeyChar <> "."c)
[color=Blue] Else[/color]
e.Handled = [color=Blue]Not Char[/color].IsDigit(e.KeyChar) [color=Blue]AndAlso[/color] e.KeyChar <> "."c
[color=Blue] End If[/color]
[color=Blue] If[/color] e.Handled [color=Blue]Then[/color]
Beep()
[color=Blue] End If[/color]
[color=Blue] End Sub[/color]
I added the Beep() so that the user gets some feedback when they press an invalid key.
There are a few issues with this rather simplistic approach, though.
</p>
- If someone is entering a decimal number between 0 and 1 they should be able to enter a "0" as the first character.
- The user is not prevented from entering more than 1 decimal point.
- The user cannot copy, paste, backspace or delete in the field as these are all illegal keys.
A better idea is probably to create much more sophisticated validation or use a control created for this purpose by another developer. There are plenty available for free from various web sites. I use, and have extended, the controls detailed in an article in Visual Studio Magazine. You need to register to download code, but it's worth it as it is a good resource.
You can register here:
http://www.ftponline.com/vsm
You can find the article and download the code here:
http://www.ftponline.com/vsm/2005_01/magazine/columns/gettingstarted
I would higly recommend all VB and VS developers to check it out.