AvacadoRancher
AvacadoRancher

Reputation: 135

KeyDown/KeyPress and Indexing

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

Upvotes: 0

Views: 726

Answers (4)

Oliver
Oliver

Reputation: 45109

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).

Upvotes: 0

scwagner
scwagner

Reputation: 4005

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.

Upvotes: 0

DRapp
DRapp

Reputation: 48159

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;
    }
 }

Upvotes: 1

Ed Swangren
Ed Swangren

Reputation: 124722

protected override void OnKeyDown( object sender, KeyEventArgs e )
{
    e.Handled = ( ( this.SelectionStart == 0 ) && ( e.KeyCode == Keys.D0) )
}

Upvotes: 0

Related Questions