0

Compelete noob working on my first app in C#. Here is what I am trying to do....

A user is going to enter an "ID" into a text box, all numbers. I have been trying to figure out how to trap a leading zero in the ID, for instance:

5031 is accepteble for ID 0827 not what we want

Basically, zero cannot be the leading number in the series. I thought, perahps this could be trapped via an index but I am stumped. Any thoughts????

-Confused Trapper

Ilmari Karonen
  • 49,047
  • 9
  • 93
  • 153
AvacadoRancher
  • 135
  • 1
  • 8
  • Could 0 be a valid ID, or must it be 4 digits (or some range of digits)? – SwDevMan81 Jul 07 '09 at 03:05
  • Thanks for all the feedback so far, it has been very helpful already. I should have noted, the range of the ID is open. It can be 3 digits, 4, even more. scwagner...I do want to black 0 as the leading digit altogether as soon as possible. – AvacadoRancher Jul 07 '09 at 12:12

4 Answers4

1

How about something like... may need to tweek it.

protected override void OnKeyPress(KeyPressEventArgs e)
{
    if( this.SelectionStart == 0 && e.KeyChar == (char)'0')
   {
        e.Handled = true;
        return;
    }
 }
DRapp
  • 47,638
  • 12
  • 72
  • 142
0
protected override void OnKeyDown( object sender, KeyEventArgs e )
{
    e.Handled = ( ( this.SelectionStart == 0 ) && ( e.KeyCode == Keys.D0) )
}
Ed S.
  • 122,712
  • 22
  • 185
  • 265
0

Is it your desire to block the 0 as they key it in, or to perform the validation after they have navigated away from the field? The problem with the solutions watching keypresses is they don't monitor the contents if an invalid value is pasted in from the clipboard.

Take a look at MaskedTextBox and OnValidating within that control and see if that will solve your problem for you.

scwagner
  • 3,975
  • 21
  • 16
0

If you like to enter just number into a box, just use a NumericUpDown instead of a TextBox. In your case it seems that your ID has always four digits. So set the minimum value to 1000 and the maximum to 9999 (or greater or to Decimal.MaxValue).

Oliver
  • 43,366
  • 8
  • 94
  • 151