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.
>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;
}
}
}