Federal09 Federal09 - 1 month ago 19
C# Question

How to block or restrict special characters from textbox

I need exclude special characters (

%,&,/,",'
etc ) from textbox

Is it possible? Should I use key_press event?

string one = radTextBoxControl1.Text.Replace("/", "");
string two = one.Replace("%", "");
//more string
radTextBoxControl1.Text = two;


in this mode is very very long =(

Answer

I am assuming you are trying to keep only alpha-numeric and space characters. Add a keypress event like this

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    var regex = new Regex(@"[^a-zA-Z0-9\s]");
    if (regex.IsMatch(e.KeyChar.ToString()))
    {
        e.Handled = true;
    }
}
Comments