Philippe Renaud
asked on
restrict keychars on textbox
Hi EE,
I need to restrict keyPress on a textBox. I only want the following :
Any digits before the dot, then after the dot only one of those: 25, 50 75
so for examples this is good:
4
34
12.25
9.50
66.75
this is wrong:
2.4
11.57
34.52
3.02
can you help ?
I need to restrict keyPress on a textBox. I only want the following :
Any digits before the dot, then after the dot only one of those: 25, 50 75
so for examples this is good:
4
34
12.25
9.50
66.75
this is wrong:
2.4
11.57
34.52
3.02
can you help ?
ASKER
what is d ?
ASKER
nevermind ..
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
if I add Cchar(Backspace) i would put it where?
ASKER
thanks, let me think about that combox Box yes.
thanks
thanks
I'd suggest deriving from the existing TextBox so that you have a resusable component.
e.g.
If you added this code to your project, then built it, you would then have a component you can drag from the ToolBox onto your form.
e.g.
Public Class QuarterlyTextbox
Inherits TextBox
Private _validKeys As New List(Of Keys) From
{
Keys.D0, Keys.NumPad0,
Keys.D1, Keys.NumPad1,
Keys.D2, Keys.NumPad2,
Keys.D3, Keys.NumPad3,
Keys.D4, Keys.NumPad4,
Keys.D5, Keys.NumPad5,
Keys.D6, Keys.NumPad6,
Keys.D7, Keys.NumPad7,
Keys.D8, Keys.NumPad8,
Keys.D9, Keys.NumPad9,
Keys.Decimal, Keys.OemPeriod
}
Private _controlKeys As New List(Of Keys) From
{
Keys.Back, Keys.Delete,
Keys.Left, Keys.Right,
Keys.Home, Keys.End
}
Protected Overrides Sub OnKeyDown(e As KeyEventArgs)
If _controlKeys.Contains(e.KeyData) Then
MyBase.OnKeyDown(e)
Return
End If
If (Not _validKeys.Contains(e.KeyData)) OrElse
(Me.Text.EndsWith(".25") OrElse Me.Text.EndsWith(".50") OrElse Me.Text.EndsWith(".75")) OrElse
(Me.Text.Contains(".") AndAlso (e.KeyData = Keys.Decimal OrElse e.KeyData = Keys.OemPeriod)) OrElse
(Me.Text.EndsWith(".") AndAlso e.KeyData <> Keys.D2 AndAlso e.KeyData <> Keys.NumPad2 _
AndAlso e.KeyData <> Keys.D5 AndAlso e.KeyData <> Keys.NumPad5 _
AndAlso e.KeyData <> Keys.D7 AndAlso e.KeyData <> Keys.NumPad7) OrElse
((Me.Text.EndsWith(".2") OrElse Me.Text.EndsWith(".7")) AndAlso e.KeyData <> Keys.D5 AndAlso e.KeyData <> Keys.NumPad5) OrElse
(Me.Text.EndsWith(".5") AndAlso e.KeyData <> Keys.D0 AndAlso e.KeyData <> Keys.NumPad0) Then
e.SuppressKeyPress = True
e.Handled = True
Return
End If
MyBase.OnKeyDown(e)
End Sub
End Class
If you added this code to your project, then built it, you would then have a component you can drag from the ToolBox onto your form.
Open in new window