Click here to Skip to main content
15,897,891 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
I have a form with lots of custom-made TextBoxes (let's call them InheritedTextBox). Now I need to set the MaxLength property based on the textbox's data binded property. The property itself has a MaxLength attribute that I need to read (that's trivial).

The problem is that the TextBox control doesn't have a Load event. So where should I call the code that sets the MaxLength property when the form is loaded? I've tried the textbox's constructor (no databindings set yet) and the TextBox.DataBindings.CollectionChanged event (doesn't get called until the textbox is disposed).

So in a nutshell:
- I bind a textbox into a datasource in designer (for example an Order entity and its property OrderID)
- The OrderID property has custom attribute MaxLength(30)
- I want that attribute's value to be set on the bound textbox's MaxLength when the form loads up

The binding don't exist when the textbox is being instantiated and there's no Load event. So what to do?


Any suggestions?
Posted
Updated 12-Aug-11 2:17am
v3

There is no such event; there is no a concept of loading of the text box. There is a read-only property System.Windows.Forms.TextBox.Text. The setter of this property fires the event System.Windows.Forms.TextBox.TextChanged. Use it — this is what you need.

—SA
 
Share this answer
 
Comments
Abhinav S 14-Aug-11 2:05am    
Fair enough. My 5.
Sergey Alexandrovich Kryukov 14-Aug-11 2:11am    
Thank you, Abhinav.
--SA
kornakar 15-Aug-11 1:53am    
I don't understand what I should do with TextChanged. I only wanted to set the MaxLength property once the form is loaded (not every time the text changes).
The Form has a Loaded event. You can use that handler and enumerate through the controls and if you find a textbox, do whatever you need to do.
 
Share this answer
 
Comments
kornakar 12-Aug-11 8:59am    
So this is impossible to do inside the control? I have no choice but to create a base form and move the logic there?
Sergey Alexandrovich Kryukov 14-Aug-11 2:15am    
It is possible, but the concept is different -- please see my answer.
--SA
Sergey Alexandrovich Kryukov 14-Aug-11 2:14am    
John, I like you answer about Schrodinger's Cat paradox!
As to this one, I'm just not sure this is what OP needs. In fact Form.Loaded event is fictional. It is simply called from its constructor. OP mentioned "text box loaded"; I assumed TextBox.TextChanged is what should work -- please see my answer.
--SA
kornakar 15-Aug-11 1:53am    
This seems the most appropriate solution. Thanks.

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