Click here to Skip to main content
15,881,898 members
Articles / Programming Languages / C#
Article

Filtered Textbox

Rate me:
Please Sign up or sign in to vote.
2.18/5 (6 votes)
9 Oct 20051 min read 49.8K   513   13   9
Demonstrates how to impliment a textbox who's input is regulated via. a regular expression.

Introduction

Have you ever needed to create a textbox that only allows you to enter numbers? Or letters? Or strings that don't start with a number? C# 2.0 addresses this point to a certain extent with the masked textbox. However, this does not help if you need to use more complex rules to define the validation.

To this end, I created a FilteredTextBox, that uses a regular expression filter to define what can be entered in the textbox. If it cannot be entered, it will not appear (unlike a post-validation, that would create an error message, or cleanup and remove invalid characters after)

Using the Code

To use the compiled componant, enter a regular expression that for any acceptable string in the textbox will create a match in the Filter property.

Adding Sound

I excluded this to enable the code to work with .NET 1.1 However, if you are using 2.0, or can do something similar in 1.1, it may be a good idea to provide audio feedback when an invalid character is typed. I did this by adding a boolean property of ShouldPlaySound and modiftying the code to match below:
C#
if (!regexFilter.IsMatch(inputText))
{
    if (PlayErrorSound)
        SystemSounds.Beep.Play();
    e.Handled = true;
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generaloptimized for filtering every char Pin
jopomo20-Nov-06 4:35
jopomo20-Nov-06 4:35 
GeneralBug in filteredTextBox_KeyPress Pin
Perry211-Apr-06 13:10
Perry211-Apr-06 13:10 
GeneralWM_PASTE Pin
tonyt9-Oct-05 20:27
tonyt9-Oct-05 20:27 
GeneralRe: WM_PASTE Pin
[ICR]9-Oct-05 21:20
[ICR]9-Oct-05 21:20 
GeneralUmm... Pin
The_Mega_ZZTer9-Oct-05 7:45
The_Mega_ZZTer9-Oct-05 7:45 
GeneralRe: Umm... Pin
[ICR]9-Oct-05 7:56
[ICR]9-Oct-05 7:56 
GeneralRe: Umm... Pin
The_Mega_ZZTer9-Oct-05 7:59
The_Mega_ZZTer9-Oct-05 7:59 
GeneralRe: Umm... Pin
[ICR]9-Oct-05 8:06
[ICR]9-Oct-05 8:06 
GeneralRe: Umm... Pin
[ICR]9-Oct-05 11:48
[ICR]9-Oct-05 11:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.