How do I stop invalid characters being typed into a TextBox?

  • Thread starter Thread starter Tim Osborne
  • Start date Start date
T

Tim Osborne

Hi

At first blush this seemed like it should be so simple. Guess again.

I want to only allow numeric characters and hexadecimal values in a TextBox,
anything else should be ignored, and maybe a beep be issued.

So I figure I need a KeyDown event and I just have to mark it as Handled,
right?

Wrong!!!!

So how do I accomplish this? I have all my controls in a UserControl BTW.

As a side note, you'd think Microsoft would have added a NumericOnly
property to their text fields by now.
How many times have I had to do numeric only validation, I've lost count.
 
Hi,


Tim Osborne said:
Hi

At first blush this seemed like it should be so simple. Guess again.

I want to only allow numeric characters and hexadecimal values in a
TextBox,
anything else should be ignored, and maybe a beep be issued.

So I figure I need a KeyDown event and I just have to mark it as Handled,
right?

Wrong!!!!

I could bet I have done it this way, why it's not working with you? In what
platform are you in?
So how do I accomplish this? I have all my controls in a UserControl BTW.

As a side note, you'd think Microsoft would have added a NumericOnly
property to their text fields by now.
How many times have I had to do numeric only validation, I've lost count.

You are right in this one, not only that but it's enough to make public a
protected property


public class NumberTextBox : TextBox
{
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.Style |= 0x2000; // ES_NUMBER
return cp;
}
}
}

cheers,
 
Ahhhhhh, well the first part of the solution is to do the checking in the
KeyPressed handler.

That way when you say e.Handled = true; it doesn't pass the event onwards.

Now I just have to figure out how to make a Beep sound.

Any ideas on that one?
 
Now I just have to figure out how to make a Beep sound.


using System.Runtime.InteropServices;

[DllImport("kernel32.dll")]
private static extern bool Beep(int freq, int dur);
Beep(3000, 200);
 
Back
Top