2

I want my textbox to never accept special chars. Only accepts space,numbers and letters. I found this code for Presskey event:

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

But it doesnt work when someone paste something in the textbox. How can I make a textChanged event equivalent?

I tried replacing the not accepted chars for "" with this function but its not working.Its showing any chars when I paste and for some reason its erasing the default initial text "text1":

 private void rsNameTextBox_TextChanged(object sender, EventArgs e)
        {
            Regex reg = new Regex(@"^[\s\dA-Za-z]+$");
            rsNameTextBox.Text = reg.Replace(rsNameTextBox.Text,"");
        }
huMpty duMpty
  • 14,346
  • 14
  • 60
  • 99
Carlos Siestrup
  • 1,031
  • 2
  • 13
  • 33
  • See this answer : http://stackoverflow.com/questions/3061475/paste-event-in-a-wpf-textbox. Note if you try checking data with the PreviewTextInput command you will find that space, backspace & delete do not cause an event - you need to check that with the PreviewKeyDown event. – PaulF Oct 14 '15 at 16:37
  • Note - to ignore the pasted input you need to call _e.CancelCommand();_ – PaulF Oct 14 '15 at 16:44

1 Answers1

0

why you are not using ShortcutsEnabled propety of the TextBox you want to prevent cut,copy and paste features.

and then you can use your code in rsNameTextBox_KeyPress

Here is the link ,How to prevent paste features in Window Form Application.

Community
  • 1
  • 1
A_Sk
  • 4,532
  • 3
  • 27
  • 51