Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » Visual C# » Restricting User Input

Restricting User Input

This article describes an approach to restricting the user’s input to letters only, numbers only, letters or numbers only, and special characters only. The approach is simple to implement and can be used whenever it is necessary to restrict a user’s response to instances where it is necessary to capture information from the user into a form’s text box control.

Author Rank :
Page Views : 29178
Downloads : 536
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
RestrictingInput.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction

This article describes an approach to restricting the user's input to letters only, numbers only, letters or  numbers only, and special characters only.
 
 

Figure 1.  Restricting User Input into Text Box Controls

Getting Started.

There is a single Win Forms application included with this download.  You may open the project and examine the project if you wish; however, the code is quite simple and will be described in the following sections of this document.  All examples were written using Visual Studio 2005 and are in C#; the same code could also be used in earlier versions of Visual Studio.

Code Example:  Restricting User Input.

The application contains a single form; the form contains four text box controls and each text box is labeled to describe the required input for the text box.  There is also a single button control which is used to terminate the application.

In order to evaluate the user's entries into the text box and to prevent the entry of restricted characters, a key press event handler is added for each of the text box controls.  The keyboard inputs submitted to the text box control are intercepted and evaluated prior to writing any information into the text box.

The first text box is restricted to allow only letters to be entered into the text box.  In order to perform this input filtering, the key press event argument is evaluated using the character structure's "IsLetter" function to determine whether or not the value keyed in is in fact a letter.  In this instance, if the character is not a letter, the key press event is disregarded by setting the handled property to true.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

{

    // allows only letters

    if (!char.IsLetter(e.KeyChar))

    {

        e.Handled = true;

    }

}

The second box is is restricted to allow only numbers to be entered into the text box.  This works in a manner consistent with the first example except instead of using  "IsLetter" it uses "IsNumber" to evaluate the input.

private void textBox2_KeyPress(object sender, KeyPressEventArgs e)

{

    // allows only numbers

    if (!char.IsNumber(e.KeyChar))

    {

        e.Handled = true;

    }

}

The third text box in the form is restricts the user input to allow only letters or numbers to be entered; special characters are not allowed.  This method uses the character structure's "IsLetterOrDigit" method to evaluate the user's input.

private void textBox4_KeyPress(object sender, KeyPressEventArgs e)

{

    // allows only letters or numbers

    if (!char.IsLetterOrDigit(e.KeyChar))

    {

        e.Handled = true;

    }

}

The last text box control restricts the user to input only special characters; this uses the same "IsLetterOrDigit" call as shown in the previous example, however, instead of looking for a negative match, it looks for a positive match.

private void textBox3_KeyPress(object sender, KeyPressEventArgs e)

{

    // allows only special characters

    if (char.IsLetterOrDigit(e.KeyChar))

    {

        e.Handled = true;

    }

}

Summary.

This article demonstrates a few different ways to restrict a user's input at the level of the form.  Aside from the examples shown in this document, one may also consider the use of masked text boxes as a means of restricting user input to a specific string format.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Good article by Terrence On January 2, 2007

Scotty,

Thanks for your article on restricting user input, it saved me a lot of time.  I needed to make any letters a user typed into a textbox capitals and your article gave me the idea on how to do it.  I changed your code as follows and it works great:

private void textbox1_KeyPress(object sender, KeyPressEventArgs e)

{
       e.KeyChar=
char.ToUpper(e.KeyChar);
}

Regards
Terry

Reply | Email | Modify 
decimal entry by Russ On March 2, 2007
Can one specify decimal entry i.e. "123.45" ?
Reply | Email | Modify 
Re: decimal entry by Scott On March 3, 2007

If you want to limit the user to keying in a valid decimal, you can do something like this:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

{

     // allows only numbers and decimals

     if (!char.IsNumber(e.KeyChar) && e.KeyChar != '.')

     {

          e.Handled = true;

     }

     // allow only one decimal place

     if (textBox1.Text.Contains(".") && e.KeyChar == '.')

     {

          e.Handled = true;

     }

}

Reply | Email | Modify 
Good Article. by Mohamed On December 3, 2007
Thanks Zakir
Reply | Email | Modify 
hmm how bout this... by Jose On December 23, 2007
Hi! I'm very new at c# really, I'm still learning, and i was wondering.. When i use that code, i can't erase qhatever i have writing, if i want to use backspace, it doesn't allow me.. How do i avoid it?? thanks! Merry Christmas!
Reply | Email | Modify 
Re: hmm how bout this... by Scott On December 23, 2007

Jose:

There are a couple of ways you can do it; you can allow all control characters, or you can allow just the backspace.  Here are examples of both:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

{

     // allows only letters or numbers or control characters

     if (!char.IsLetterOrDigit(e.KeyChar) && !char.IsControl(e.KeyChar))

     {

          e.Handled = true;

     }

}

private void textBox2_KeyPress(object sender, KeyPressEventArgs e)

{

     // allows only letters or numbers or a backspace

     if (!char.IsLetterOrDigit(e.KeyChar) && e.KeyChar.ToString() != "\b")

     {

          e.Handled = true;

     }

}

Reply | Email | Modify 
Re: Re: hmm how bout this... by Jose On December 27, 2007
Thanks a million!! That's exactly what i was looking for!
Reply | Email | Modify 
Good article by mamatha On February 25, 2008
Its a very good article
Reply | Email | Modify 
Re: Good article by Scott On February 26, 2008

Hey thanks, I appreciate it.

Scott

Reply | Email | Modify 
Re: Re: Good article by mamatha On February 26, 2008

can we restrict the user to enter in the range like >'x' and less than 'y'

 

Reply | Email | Modify 
Re: Re: Re: Good article by Scott On February 27, 2008

Sure; you can limit to specifics or a range of values using the ascii decimal value.  For example to limit a response to capital A through capital E, you'd use this:

// allows only Letter between A and E

if (e.KeyChar < 65 || e.KeyChar > 69)

{

  e.Handled = true;

}

Reply | Email | Modify 
Re: Re: Re: Good article by Scott On February 27, 2008

Sure; you can limit to specifics or a range of values using the ascii decimal value.  For example to limit a response to capital A through capital E, you'd use this:

// allows only Letter between A and E

if (e.KeyChar < 65 || e.KeyChar > 69)

{

    e.Handled = true;

}

Reply | Email | Modify 
Re: Re: Re: Good article by Scott On February 27, 2008

Sure; you can limit to specifics or a range of values using the ascii decimal value.  For example to limit a response to capital A through capital E, you'd use this:

// allows only Letter between A and E

if (e.KeyChar < 65 || e.KeyChar > 69)

{

     e.Handled = true;

}

Reply | Email | Modify 
Re: Re: Re: Re: Good article by mamatha On February 27, 2008

i actually want a number entered in the textbox to be in between eg 1000 and 2000

Can i restrict him while entering in the textBox Itself

Reply | Email | Modify 
Re: Re: Re: Re: Re: Good article by Scott On February 27, 2008

Well, no, since you are dealing with multiple characters, you'd have to do it somewhere else rather than in the keypress.  For example, if you wanted to limit the input to between 1000 and 2000, you could limit them to numeric entry in the keypress handler and then use the control's validate event to check final value entered into the textbox.  You'd also want to set the maximum size of the textbox to four so the user can't enter more than four characters.

private void textBox8_KeyPress(object sender, KeyPressEventArgs e)

{

     // allows only numbers

     if (!char.IsNumber(e.KeyChar))

     {

          e.Handled = true;

     }

}

private void textBox8_Validated(object sender, EventArgs e)

{

     int temp = Convert.ToInt32(textBox8.Text);

     if (temp < 1000 || temp > 2000)

     {

          textBox8.Text = "OUT OF RANGE";

     }

}

Reply | Email | Modify 
Thanks by mamatha On February 27, 2008
i am really thankful to you ...Thanks a lot for the reply
Reply | Email | Modify 
allowing either lower or upper case letters by Becky On March 28, 2009
I need to allow my customers to input either lower or upper case letters to still get an applied discount. Ideas
Reply | Email | Modify 
Re: allowing either lower or upper case letters by Scott On March 28, 2009
Becky:

This will allow upper or lower case characters and still let the user use backspace (to correct):

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
   if (!char.IsLetter(e.KeyChar) && !char.IsControl(e.KeyChar))
   {
      e.Handled = true;
   }
}
Reply | Email | Modify 
how to enter only numbers?? by vibha On July 30, 2009
how to enter only numbers,all other keys in the keyboard should be disabled in a c program
Reply | Email | Modify 
Nice article by Lalitha On September 3, 2010
Thank  you for posting this article.
Reply | Email | Modify 
Great Article by Adolf On November 18, 2010
Thanks a lot for all of your comments, they save my time a lot
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.