简体   繁体   中英

Textbox without special chars

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,"");
        }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM