User Controls


User Controls

Deriving from an existing control is one way to reuse it, but the most popular form of reuse for a control is simple containment, as you're accustomed to doing when building custom forms using existing controls. A user control is a way to contain a set of other controls for reuse as a set, producing a kind of "subform." For example, imagine that we wanted a control that composed our FileTextBox control with a " " button for browsing. In use, it would look like the one shown in Figure 8.21.

Figure 8.21. A Sample User Control in Action

It's hard to tell from the picture, but as far as the form in Figure 8.21 is concerned , it's containing only a single control (named FileBrowseTextBox). The control is a user control because it derives from the UserControl base class and contains two other controls: a FileTextBox control and a Button control.

To create a custom user control, you right-click on your project in Solution Explorer, choose Add Add User Control, and press OK. [7] When you do, you'll get the design surface for your user control to arrange with controls, as shown in Figure 8.22.

[7] If you'd like to start a new project to hold user controls, you can do so with the Windows Controls Library project template in the New Project dialog.

Figure 8.22. A New User Control

Building a user control that brings the FileTextBox together with a browse button is a matter of dropping each onto the form and arranging to taste. Also, to enable browsing, you'll probably want to use an instance of the OpenFileDialog component, capturing all that functionality into a single user control for reuse, as shown in Figure 8.23.

Figure 8.23. The FileBrowseTextBox User Control in the Designer

All the control arranging that you're already accustomed to ”such as anchoring and docking ”works the same way in a user control as in a custom form. You also use the same techniques for setting properties or handling events. After arranging the existing controls and components on the user control design surface, you simply write a tiny chunk of code to handle the click on the browse button to make it all work:

 void browseButton_Click(object sender, EventArgs e) {   if( this.openFileDialog1.ShowDialog() == DialogResult.OK ) {     fileTextBox1.Text = this.openFile.FileName;   } } 

User controls allow you to build reusable controls using the same tools you use when building forms, but with the added advantage of being able to drop a user control onto anything that can contain controls, including container controls, forms, and even other user controls.



Windows Forms Programming in C#
Windows Forms Programming in C#
ISBN: 0321116208
EAN: 2147483647
Year: 2003
Pages: 136
Authors: Chris Sells

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net