How to block special characters in a TextBox?

Ddd
Posted by Ddd under Windows Forms category on | Points: 40 | Views : 15413
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//define a string containing special characters
string arr = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
for (int k = 0; k < arr.Length; k++)
{
if (e.KeyChar== arr[k])
{
MessageBox.Show("special characters not allowed");
e.Handled = true;
break;

}
}
}

//Note:

// I have changed the looping variable from i to k. I hope that it wotks fine now.

Comments or Responses

Posted by: T.saravanan on: 1/22/2011 Level:Silver | Status: [Member] [MVP] | Points: 10
Hi Dinesh.K,

Nice Try.But in our website square brace of 'i' is refer italic format.So in your code that is missing.
Change the integer variable like...


for(int x=0; x < arr.Length; x++)
{
if(e.KeyChar == arr[x])
{
MessageBox.Show("special characters not allowed");
e.Handled = true;
break;
}
}


Finally my suggestion post your code inside the code tag.

Posted by: Ddd on: 1/22/2011 Level:Silver | Status: [Member] | Points: 10
Hi T.Saravanan.

I have changed the looping variable from i to k. I was wondering how the variable i was
omitted in the condition. anyway, thanks for the suggestion.
Posted by: Karaniscool on: 1/25/2011 Level:Starter | Status: [Member] | Points: 10
If we can write a regex expression and validate the keyed entry against, ten would that be faster?
Posted by: Softnetalake on: 1/3/2012 Level:Starter | Status: [Member] | Points: 10
ok.but i need to block all other special characters but not '/'.how can i do that.?

Login to post response