Controls are supposedly one of the hottest features in Visual Basic version 5, but here we are in Chapter 9 with very little sign of them. Well, the time has come. But first a little history.
The previous edition of this book presented a CEditor class. It had a Create method that took a TextBox or RichTextBox control as an argument (we’ll assume RichTextBox control in this discussion). Once it had a reference to an internal RichTextBox control, it hid the members it didn’t need to expose, changed many of the members it did expose, and added new members not available in rich text boxes. I called this class a “control” because I was trying to emulate the behavior of a real control, but using it as a control required a certain suspension of disbelief. The user had to set some of the properties of the delegated rich text box at design time, but some rich text box properties were illegal for delegated controls. Once the rich text box was handed off to the CEditor class at run time, the user wasn’t supposed to touch the original rich text box again. All interaction was supposed to be through CEditor, but there were exceptions because CEditor couldn’t do events.
In short, the whole scheme relied on conventions, and that’s a pretty weak basis for any design. Your working assumption should be that if there’s any possible way to do something wrong, some user will find that way. Your job is to define your component so that the component users can’t do anything wrong. It’s not a matter of catching mistakes after they’re made—don’t even give them a syntax for making mistakes. The new UserControl gives you a flexible way of at least approaching this goal. The XEditor control uses delegation in a manner very similar to the original CEditor, but now you have the tools to make it be a control, not just act like one.
If you look closely at a TextBox control, you will see that it’s actually two controls in one: an entry-field control and an editor control, depending on whether you set the MultiLine property. In entry-field mode, a text box doesn’t need properties like ScrollBars and Locked. Similarly, in editor mode, it doesn’t need
properties like PasswordChar and MaxLength. Other TextBox properties are shared (although some are more useful in one mode than in the other). The RichTextBox control is clearly better suited for editing than for data entry, but it inherits a lot of characteristics from TextBox for compatibility.
Coding the XEditor control consists of first creating the control and then passing on all the standard editing features of a text box. After that, you can start adding goodies.