How to block or restrict special characters from a text box

I need to exclude special characters ( %,&,/,",' , etc.) from the text box

Is it possible? Should I use the key_press event?

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

in this mode is very long = (

+7
c # winforms
source share
5 answers

I assume that you are trying to save only alphanumeric and spatial characters. Add a keystroke event like

 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; } } 
+12
source share

you can use this:

 private void textBoxSample_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = !char.IsLetter(e.KeyChar) && !char.IsDigit(e.KeyChar); } 

it blocks special characters and accepts only int / numbers and characters

+3
source share

In the code below, only numbers, letters, backspace, and space are allowed.

I turned on VB.net because there was a complicated treatment that I had to deal with.

FROM#

 private void textBoxSample_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = e.KeyChar != (char)Keys.Back && !char.IsSeparator(e.KeyChar) && !char.IsLetter(e.KeyChar) && !char.IsDigit(e.KeyChar); } 

Vb.net

 Private Sub textBoxSample_KeyPress(sender As Object, e As KeyPressEventArgs) Handles textBoxSample.KeyPress e.Handled = e.KeyChar <> ChrW(Keys.Back) And Not Char.IsSeparator(e.KeyChar) And Not Char.IsLetter(e.KeyChar) And Not Char.IsDigit(e.KeyChar) End Sub 
+2
source share

You can use the "Text Changed" event (I BELIEVE (but not sure) that this fires when copying / pasting).

When an event is triggered by a method call, say PurgeTextOfEvilCharacters ().

This method has an array of characters that you want to "block". Go through each .Text character of the TextBox control, and if the character is found in your array, you do not want it. Rebuild the line with the characters "okay" and you will go well.

I bet on the best way, but it seems good to me.

0
source share

best for me:

 void textBoxSample_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = Char.IsPunctuation(e.KeyChar) || Char.IsSeparator(e.KeyChar) || Char.IsSymbol(e.KeyChar); } 

it will be more useful to include the delete and reset keys ... etc.

0
source share

All Articles