views:

336

answers:

4

Hi everyone. 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

A: 
protected override void OnKeyDown( object sender, KeyEventArgs e )
{
    e.Handled = ( ( this.SelectionStart == 0 ) && ( e.KeyCode == Keys.D0) )
}
Ed Swangren
+1  A: 

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
A: 

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
A: 

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