This website completely moved to new platform. For latest content, visit www.programmingposts.com

Search this Site

20 Jan 2013

Textbox Validation using KeyPress Event in C#

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

KeyPressEvent_img1

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

  1. This is awesome!! really helpful for me. Thanks for sharing with us. Following links also helped me to complete my task.

    http://www.mindstick.com/Blog/322/TextBox%20Validation%20in%20C%20Net

    http://www.codeproject.com/Articles/220519/Numbers-or-Characters-only-Textbox-Validation-in-C

    ReplyDelete

Thanks for your comments.
-Sameer