Click here to Skip to main content
15,923,051 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I want to allow user to only enter string values in textbox but my code is not working well

C#
string allowedCharacterSet = "bcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\b\n\t";

        if (allowedCharacterSet.Contains(e.Key.ToString() ))
        {

        }
        else
        {
            e.Handled = true;
        }
Posted
Comments
Richard C Bishop 29-May-13 16:01pm    
You are completely confused on what you are attempting to do. No worries, it is simple to accomplish this task. Simply use a reg ex to only allow alpha characters.
Sergey Alexandrovich Kryukov 29-May-13 17:12pm    
Formally, the request makes no sense. Please see the first line of my answer.

However, if you remove one sloppy word from the post, it does make some sense, and I think finding out the implementation is not that trivial, for a beginner.
Therefore, please see the rest of my answer.

—SA

1 solution

It is already totally impossible for a user to enter anything except a string value. Case closed.

However, if you want to allow only certain characters from your user input, and if you are talking about some text box, you should handle the event System.Windows.Controls.Primitives.TextBoxBase.TextChanged:
http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.textboxbase.textchanged.aspx[^].

With this event, you have the opportunity to cancel the change. Please see:
http://msdn.microsoft.com/en-us/library/system.windows.controls.textchangedeventhandler.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.controls.textchangedeventargs.aspx[^].

Here is how: you need to assign the property System.Windows.Controls.TextChangedEventArgs.Handled to true:
http://msdn.microsoft.com/en-us/library/system.windows.routedeventargs.handled.aspx[^].

You are about to make one more mistake: to filter out backspace, which is, by some historical reasons, is considered as a character. Its code point is 8. Allow it, too.
Good luck,
—SA
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900