views:

81

answers:

4

Hi,

I have set the MaxLength property of a textbox in my windows forms application to 10

I am populating the textbox by reading from a file. However if a read string which is more than 10 characters the textbox still gets populated. But when I manually try to enter a string it works fine (that is, it does not allow more than 10 characters to be entered).

Why is there a difference between these two behaviors? How can I populate my textbox from the file and still have the MaxLength property to be working?

Thanks, Viren

A: 

You'll have to limit it programatically. That's simply the way the browsers treat HTML. Sorry :(

Unfortunately, the HTML spec doesn't offer any guidance on this issue (that I can find) so the browser makers have settled on this behavior.

http://www.w3.org/TR/html401/interact/forms.html#h-17.4

Asaph
The question is regarding a windows forms app, not html. Though, the resolution is similar (almost identical :)
Metro Smurf
YES Asaph. I am sorry that I forgot to mention C# Windows Form GUI application. My bad. Anyways its similar as pointed out by Metro Smurf
VP
A: 

At the very worst, you could try to limit your data to 10 characters when you are binding to the textbox:

txtMyTextbox.Text = Left(myData, 10)
Jason
+3  A: 

From the TextBoxBase.MaxLengthProperty specs:

In code, you can set the value of the Text property to a value that has a length greater than the value specified by the MaxLength property. This property only affects text entered into the control at run time.

In other words, you must limit the amount of text in code when pulling from a data source.

For Example:

string text = "The quick blue smurf jumped over the brown fox.";
textBox1.Text = text.Substring( 0, textBox1.MaxLength );
Metro Smurf
A: 

It's never wise to rely entirely on instant validation of values - you should always validate the final value as well. For example, i've seen people regularly using KeyUp/KeyDown/KeyPress events to disallow various characters, and then forgetting that people regularly use copy-and-paste (which negates the intended validation).

CodeByMoonlight