In this post we will see the textbox validation using KeyPress Event in Windows C# . For this i am taking two textboxes on a form one is  txt_Name and another is  txt_Mobile . 

And i am taking one error provider on form. The Form designed as shown in figure below.

keypress-event-winforms-1
Now the C# code is like this.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace KeyPressEvent
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            txt_Mobile.MaxLength = 10;
        }

        private void txt_Name_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsLetter(e.KeyChar) && Convert.ToInt32(e.KeyChar) != 8)
            {
                errorProvider1.SetError(txt_Name, "Only letters allowed");
                e.Handled = true;
                txt_Name.Focus();
            }
            else
            {
                errorProvider1.Clear();
            }
        }

        private void txt_Mobile_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar) && Convert.ToInt32(e.KeyChar) != 8)
            {
                errorProvider1.SetError(txt_Mobile, "Only Numbers Allowed");
                e.Handled = true;
                txt_Mobile.Focus();
            }
            else
            {
                errorProvider1.Clear();
            }
        }
    }
}

In the above code we have written keypress events for both the textboxes txt_Name and txt_Mobile .

Keypress Event for txt_Name is to validate Textbox so that it should allow only characters . otherwise errorProvider shows a error with a message “Only letters allowed ” .

Keypress Event for txt_Mobile is to validate Textbox so that it should allow only Numbers . otherwise errorProvider shows a error with a message “Only Numbers allowed ” .

We can fix the maximum lenth of the txt_Mobile to 10. you can see the line of code

txt_Mobile.MaxLength = 10;

And the code

Convert.ToInt32(e.KeyChar) != 8

is to accept back space in a textbox . if this line of code is not present, textbox wont allow backspace also.

1 thought on “Textbox Validation using KeyPress Event in C#”

Leave a Reply

Your email address will not be published. Required fields are marked *