DoIt
DoIt

Reputation: 3448

Raise a Text box event when fourth digit is entered

I am working on a c# windows forms application and I have a text box which accepts a maximum of four character for which I am trying to raise am event when fourth character.

I tried to include it in KeyPress event but to raise the event I had to press a key after all the four characters are entered

private void txtFourC_KeyPress(object sender, KeyPressEventArgs e)
{
 if ( txtFourC.TextLength == 4)
    {
       //code here
    }
 }

Is there a better way to do this may be other than Key_Press

Upvotes: 1

Views: 808

Answers (4)

Selim Balci
Selim Balci

Reputation: 910

private void txtFourC_TextChanged(object sender, KeyEventArgs e)
{
    if(txtFourC.Text.Length == 4)
    {
        //do your control here.
    }
}

Upvotes: 0

Munawar
Munawar

Reputation: 2587

If the purpose is to restrict input to maximum 4 characters then its best to set MaxLength property. txtFourC.MaxLength=4

However, if you want to show message when 4th character is typed in then you may use KeyUp event instead KeyPress.

private void txtFourC_KeyUp(object sender, KeyEventArgs e)
{
   if(txtFourC.Text.Length ==4)
   {
     MessageBox.Show("Reached max length");
   }
}

Upvotes: 0

Ace Indy
Ace Indy

Reputation: 109

Or use the event to f.e. jump to the next field after the 4th digit is typed. So use the TextChanged event and check for TextLength property to know length of text in the control and activate the next field.

Upvotes: 0

Reza Aghaei
Reza Aghaei

Reputation: 125257

To limit the maximum number of characters that users can type or paste into the TextBox, it's enough to set MaxLength property.

If you don't want to limit the user, but you want to be notified when the user entered more than 4 characters, handle TextChanged event and check for TextLength property to know length of text in the control.

Upvotes: 3

Related Questions