Click here to Skip to main content
15,909,091 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi! all,
I have an application where i have to enter some characters in a textbox, how can i validate it so that the textbox doesn't accept a space in the beginning of the textbox.
Posted

Hi,

Handle the KeyPress event for this textBox and put a single condition like.
C#
if (textBox1.Text.Length==0 && e.KeyChar==' ')
{
     e.Handled = true;
}
else
{
     e.Handled = false;
}


Here textBox1 is your textbox. This code will prevent user to enter space at begining of TextBox.

Now, If you want to validate the data
Then You need to check first character of TextBox whether it's a space or not.
You can find first character like this
C#
char FChar=textBox1.Text.Substring(0,1);


Regards
AR
 
Share this answer
 
v2
C#
if (textBox1.Text.Length==0 && e.KeyChar==' ')
{
     e.Handled = true;
}
else
{
     e.Handled = false;
}
 
Share this answer
 
v2
Comments
V!jAy pAnT 28-Jun-12 5:33am    
what is e here?? plz reply
Hi,

Handle the KeyPress event for this textBox and put a single condition like.

C#
if (textBox1.Text.Length==0 && e.KeyChar==' ')
{
     e.Handled = true;
}
else
{
     e.Handled = false;
}



Here textBox1 is your textbox. This code will prevent user to enter space at begining of TextBox.

Now, If you want to validate the data
Then You need to check first character of TextBox whether it's a space or not.
You can find first character like this

C#
char FChar=textBox1.Text.Substring(0,1);
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900