Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
See more:
Good evening to everyone............
I just need a code to validate a textbox that should not allow more than 200 characters.

Can anyone step forward
Posted
Comments
Shahin Khorshidnia 28-Feb-12 8:14am    
Please Tag your question. WinForm? ASP.Net? WPF? ....?

Hello,

Set it's MaxLenght to 200
 
Share this answer
 
Handle the TectChanged event, and do something like this:

C#
TextBox ctrl = sender as TextBox;
if (ctrl.Length > 200)
{
    ctrl.Text = ctrl.Text.Substring(0,200);
}
labelCtrl.Text = string.Format("{0} of 200 characters", ctrl.Text.Length);
 
Share this answer
 
v2
Comments
vivekx2 28-Feb-12 8:17am    
thanks for ur support....but i need to display the error message in label below the textbox....
so how to call the label in your coding...
#realJSOP 1-Mar-12 9:24am    
Seriously? You couldn't figure that out on your own? Answer updated.
Member 8385328 1-Dec-15 19:02pm    
Why should not I do it like this (without TextBox ctrl = sender as TextBox;):

private void textBox1_TextChanged(object sender, EventArgs e)
{

if (textBox1.TextLength > 30)
{
textBox1.Text = textBox1.Text.Substring(0, 30);
}
labelCtrl.Text = string.Format("{0} of 200 characters", textBox1.Text.Length);
}
Another solution would be to use the .Validating event from the Control. You can than use a ErrorProvider-Control to show the user what he is doing wrong.

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating.aspx[^]
 
Share this answer
 
set MaxLength property of the textbox to 200
 
Share this answer
 

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