Controls


Often, after arranging a set of controls just right, you need that group of controls elsewhere. In that case, you can copy and paste the controls between forms, making sure that all the settings are maintained , or you can encapsulate the controls into a user control for a more robust form of reuse. User controls are containers for other controls and are best created in a Windows Control Library project.

To add a Windows Control Library project to an existing solution, you use the Add New Project item from the menu you get when you right-click on your WinForms application's solution in Solution Explorer. You'll also want to make sure that you're creating the new project in the same location as your existing solution, because VS.NET defaults to placing new projects one folder too far up the hierarchy in most cases. Figure 1.11 shows how to add a new project called MyFirstControlLibrary to an existing solution called MySecondApp.

Figure 1.11. Adding a New Project to an Existing Solution

After you've created a control library project, you'll be presented with a user control design surface very like that of a form. The only real difference is that there's no border or caption, which will be provided by the form host of your new control. The code generated by the Wizard looks very much like the code generated for a new form except that the base class is UserControl instead of Form:

 
 Public Class UserControl1   Inherits System.Windows.Forms.UserControl   Public Sub New()       InitializeComponent()   End Sub   Private Sub InitializeComponent()   End Sub End Class 

In the Designer, you can drop and arrange any controls on the user control that you like, setting their properties and handling events just as on a form. Figure 1.12 shows a sample user control as seen in the Designer.

Figure 1.12. A User Control Shown in the Designer

When you're happy with your control, you can add it to the Toolbox by dragging the user control's source code file, in this case UserControl1.vb, from the Solution Explorer to the Toolbox. When it's there, you can drag and drop it onto the forms of your choice, setting properties and handling events via the Property Browser just as with any of the built-in controls. Figure 1.13 shows the user control from Figure 1.12 hosted on a form.

Figure 1.13. Hosting a User Control

User controls aren't the only kind of custom controls. If you're interested in drawing the contents of your controls yourself, scrolling your controls, or getting more details about user controls, you'll want to read Chapter 8: Controls.



Windows Forms Programming in Visual Basic .NET
Windows Forms Programming in Visual Basic .NET
ISBN: 0321125193
EAN: 2147483647
Year: 2003
Pages: 139

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