Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Allow copy/paste feature to the textbox in windows forms

My application contains a textbox where we need not to allow special characters.I had written the logic in Keypress event of textbox. But the textbox is not allowing to copy/paste feature.How can I make to allow the copy/paste feature from the following code in keypress event.Mycode is as follows :

private void textBox4_KeyPress(object sender, KeyPressEventArgs e)
{
    if(comboBox10.Text == "Abc")
    {
        if (e.KeyChar != (char)Keys.Back && !char.IsSeparator(e.KeyChar) && !char.IsLetter(e.KeyChar) && !char.IsDigit(e.KeyChar))
        {
            MessageBox.Show("Special characters are not allowed");
            e.Handled = true;
        }
        //e.Handled = e.KeyChar != (char)Keys.Back && !char.IsSeparator(e.KeyChar) && !char.IsLetter(e.KeyChar) && !char.IsDigit(e.KeyChar);
    }
}

As of now the above code is working fine for not allowing the special characters but, When I press ctrl+v the messagebox is displaying.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

private void textBox4_KeyPress(object sender, KeyPressEventArgs e)
{
    // Check if Ctrl pressed
    if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
    {
        return; // Allow Copy/Paste
    }

    if (comboBox10.Text == "Abc")
    {
        if (e.KeyChar != (char)Keys.Back && !char.IsSeparator(e.KeyChar) && !char.IsLetter(e.KeyChar) && !char.IsDigit(e.KeyChar))
        {
            MessageBox.Show("Special characters are not allowed");
            e.Handled = true;
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading