Creating User Controls

Creating User Controls

C# gives you the capability to build controls for both Windows and Web applications. We're going to do that in this chapter, starting with Windows custom controls, called user controls. Later in the chapter we'll see how to create custom controls for Web applications, called Web user controls.

Using Visual Studio .NET, you can create your own user controls for use in Windows forms. For example, you might want such a control to display a day planner or a mortgage amortization calculator. Building reusable user controls lets you avoid the tedium of rebuilding your day planner or mortgage calculator in multiple applicationsyou just need to drop your user control onto the appropriate form.

At design time, user controls appear much like mini-Windows forms, and you can add standard Windows forms controls (such as buttons in a mortgage calculator) to them to create a composite control. Or you can draw the appearance of the control yourself using its Paint event. You can also make use of the user control's built-in events, like the Click event, to support your events in your user control.

We'll create an example user control now that will support a custom property, method, and event, just as you'd expect a control to do. To follow along, choose File, New Project to open the New Project dialog box that you see in Figure 11.1. This time, select the Windows Control Library item, naming this new project ch11_01, as you see in Figure 11.1 (note that you can also add a new user control to an existing application by choosing Project, Add User Control).

Figure 11.1. Creating a user control with the New Project dialog box.

graphics/11fig01.jpg

THE PAINT EVENT

The Paint event occurs when an object, such as a control or a form, needs to be (re)drawn. In Windows applications, the Paint event handler is passed a System.Windows.Forms.PaintEventArgs object named e , and you can access a Graphics object as e.Graphics . The Graphics class, one of the largest of the FCL classes, is used for drawing. For example, to draw a rectangle, call e.Graphics.DrawRectangle ; to draw a line, call e.Graphics.DrawLine ; to draw an image, call e.Graphics.DrawImage ; to draw a filled polygon, call e.Graphics.FillPolygon ; and so on.


Clicking the OK button in the New Project dialog box creates and opens a new user control in the IDE, as you see in Figure 11.2. As you can see in the figure, the new user control is rectangular, just like a Windows form, and in fact it acts much like a mini-Windows form. In this example, we're going to use a Windows label control to cover most of the user control, so add that label to the user control now as you see in the figure.

Figure 11.2. A user control at design time.

graphics/11fig02.jpg

We'll start coding this user control by adding a new property to it; in this case, we'll add a new property named DisplayColor that will set the color of the label in the middle of the user control.

Giving Properties to User Controls

When you create a control for our new user control's class, assigning a value to the control's DisplayColor property will set the color of the control. The control's color is determined by setting the background color of the label in the center of the control. To implement the DisplayColor property, open the user control's code in a code designer now. As you can see in the code designer, the new user control class, UserControl1 , is based on the System.Windows.Forms.UserControl class:

 
 public class UserControl1 : System.Windows.Forms.UserControl {   private System.Windows.Forms.Label label1;     .     .     . } 

We can create the new DisplayColor property like any other property, using get and set accessor methods . In this case, DisplayColor is going to be the color displayed by the label in this user control. To set a color, we use the label's BackColor property (which takes objects of the System.Drawing.Color class) this way:

 
 public class UserControl1 : System.Windows.Forms.UserControl {   private System.Windows.Forms.Label label1;   #region Component Designer generated code     .     .     .  public Color DisplayColor   {   get   {   return label1.BackColor;   }   set   {   label1.BackColor = value;   }   }  } 

This code implements the DisplayColor property in the user control; now you can assign or retrieve System.Drawing.Color objects using this property. Before seeing this property at work, we'll add a new method to our control as well.

Giving Methods to User Controls

You can add methods to user controls as easily as you can add properties. As with other objects, you just add the code for the new method to the user control's class. To make that method accessible outside the control, make it a public method.

In this example, we'll add a method named DrawText , which will display the text you pass to it in the label control. That's easy enough to write; here's what that method looks like in the new user control's code:

 
 public class UserControl1 : System.Windows.Forms.UserControl {   private System.Windows.Forms.Label label1;   #region Component Designer generated code     .     .     .   public Color DisplayColor   {     get     {       return label1.BackColor;     }     set     {       label1.BackColor = value;     }   }  public void DrawText(string text)   {   label1.Text = text;   }  } 

That adds a new method to our user control. And you can also add events, coming up next .

Giving Events to User Controls

You add events to user controls as we saw in Chapter 4, "Handling Inheritance and Delegates"you just use a delegate and the event statement to create a new event. In this example, we'll add an event named NewText to our user control, which will occur when the text in the control changes. As we've written the user control, the only way of changing the text in the control is with the DrawText method, so we'll fire the NewText event in that method's code:

 
 public class UserControl1 : System.Windows.Forms.UserControl {   private System.Windows.Forms.Label label1;   #region Component Designer generated code  public delegate void NewTextDelegate(object UserControl1, string text);   public event NewTextDelegate NewText;  public Color DisplayColor   {     get     {       return label1.BackColor;     }     set     {       label1.BackColor = value;     }   }   public void DrawText(string text)   {     label1.Text = text;  NewText(this, text);  } } 

At this point, we've given our new user control a property, DisplayColor , a method, DrawText , and an event, NewText . With these custom items, our user control is ready to use, just as you'd use any other Windows control.

Putting User Controls to Work

In order to make our user control available to other Windows projects, it has to be compiled into .DLL form (actually a .NET assembly with the extension .DLL). To compile it, choose Build, Build Solution in the IDE. After you do, you can use this new user control in other projects by adding a reference to the control in the other project.

To see that at work, we'll create a new Windows application project now, grouping it with our user control by adding that new application to the current solution in the IDE. IDE solutions can hold multiple projects; our current solution only holds the user control project, ch11_01, but you can choose File, Add Project, New Project to add a new Windows application to this solution. Name that new application ch11_02, as you see in Figure 11.3.

Figure 11.3. Adding a new project to test the user control.

graphics/11fig03.jpg

This new Windows application will display our user control at runtime. Because you can't run a user control directly, you have to make the new Windows application, ch11_02, the startup project for the current solution. You do that by selecting that project in the Solution Explorer, right-clicking it, and then choosing Set as Startup Project. (Alternatively, select the project and choose Project, Set as Startup Project from the IDE's main menu system.)

We'll need to add our new user control to the Windows application's main form. The IDE makes it easy to do that when you add a reference to our user control, which will make our user control appear in the toolbox like any other Windows control. To add a reference to the user control, ch11_01, in the Windows application's toolbox, right-click the ch11_02 application's References item in the Solution Explorer and choose Add Reference, opening the Add Reference dialog box you see in Figure 11.4. To add a reference to the UserControls project, click the Projects tab and double-click the UserControls item, which adds that a reference to the Selected Components box at the bottom of the dialog box. Finally, click OK.

Figure 11.4. The Add Reference dialog box.

graphics/11fig04.jpg

This adds the user control to the toolbox's My User Controls tab, as you see in Figure 11.5. (In earlier versions of Visual Studio .NET, the user control is added to the Windows Forms tab.) To add a user control to the main form in the ch11_02 Windows application, just drag the control from the toolbox, creating a control named userControl11 (the first object of the UserControl1 class).

Figure 11.5. Adding a user control to a Windows application.

graphics/11fig05.jpg

Note also that the properties window displays the properties of the new user control, including the custom DisplayColor property, as you see in Figure 11.5. Because we've made the type of that property System.Drawing.Color , the IDE will display drop-down lists of colors you can select for the DisplayColor property, just as it does for any property that takes System.Drawing.Color objects (such as the BackColor property of most controls). In this case, we've selected aquamarine for the DisplayColor property, which appears in the label in the center of our user control, as you can see in Figure 11.5 (in stunning black and white).

You can also call the methods of our new user control, userControl11 , such as the DrawText method. To let the user call this method, add a new button with the caption Click Me! to the Windows application, ch11_02, and add this code to the button's Click event handler (you might note that as you add the code to call DrawText , the IDE's IntelliSense facility will list the type of the data you pass to DrawText , just as it would for any method built into a control you're working with):

 
 private void button1_Click(object sender, System.EventArgs e) {  userControl11.DrawText("User Controls!");  } 

When the user clicks the Click Me! button, the text "User Controls!" is passed to the user control's DrawText method, which displays that text in the label in the user control, as you can see in Figure 11.6.

Figure 11.6. Using the DrawText method.

graphics/11fig06.jpg

When you change the text in the label in the user control by calling the DrawText method, the control's NewText event fires. You can add code to that event as you can any control event. Simply select the user control in the IDE, click the lightning button in the properties window to see its events, and double-click the NewText event to open its event handler in a code designer. In this case, we will make the NewText event handler for userControl11 to display the new text in a message box this way:

 
 private void userControl11_NewText(object UserControl1, string text) {  MessageBox.Show("New text: " + text);  } 

Now when you run the Windows application and click the Click Me! button, the NewText event occurs and that event's handler displays the new text in the message box we've added to the Windows application. You can see the results in Figure 11.7.

Figure 11.7. Handling the NewText event.

graphics/11fig07.jpg

That's how to make use of a user control from another application in the same solution. But what if you want to use a user control in a project not in the same solution? In that case, you can still use a reference to the user control's .DLL file, ch11_01.dll. This time, the user control won't appear in the new project's toolbox by default. To add a user control to a Windows form, you can create a ch11_01.UserControl1 object in code, and then add an event handler and display the control like this:

 
 ch11_01.UserControl1 uc1; private void Form1_Load(object sender, System.EventArgs e) {   uc1 = new ch11_01.UserControl1();   uc1.DisplayColor = System.Drawing.Color.Aquamarine;   uc1.Top = 100;   uc1.Left = 100;   uc1.NewText += new ch11_01.UserControl1.NewTextDelegate(uc1_NewText);   Controls.Add(uc1); } private void uc1_NewText(object sender, string text) {   MessageBox.Show(text); } private void button1_Click(object sender, System.EventArgs e) {   uc1.DrawText("User Controls!"); } 

Alternatively, you can add the user control to the toolbox if you take a few extra steps. To do that, select Tools, Add/Remove Toolbox Items in the IDE, and then select the .NET Framework Components tab. Browse to and select ch11_01.dll, make sure the check box for ch11_01.dll is checked in the .NET Framework Components tab, and then click OK. The user control should appear at the bottom of the toolbox, ready for use in Windows applications like any other control. You can publish your user control in this way; just distribute its .DLL file and programmers can add it to their IDE installation's toolbox using this technique.

SHOP TALK : ACTIVEX CONTROLS AND C#

The idea behind user controls is simple: code re-use. The idea is that you write it once and use it many times. But what about working with earlier components also designed for code re-useCOM components and ActiveX controls of the kind developed with previous versions of Visual Studio? Can you use them in Visual Studio .NET? When you try to use or import these items, the main issue is one of security, something that Microsoft is desperately trying to shore up. COM components are not by nature safe ( especially because they can use pointers extensively) in the same way that .NET components are, and often have to be substantially rewritten to fit in with .NET. Although it's possible to rewrite COM components for use in .NET, my experience is that you're usually better off rewriting the component's functionality using .NET code in the first place. On the other hand, ActiveX .OCX controlsdesigned for uses that included the Internetwere automatically made much more secure, which means that it is fairly easy to import such controls into the .NET IDE. To import an ActiveX control, select Tools, Add/Remove Toolbox Items, but this time select the COM Components tab in the Customize Toolbox dialog box, not the .NET Framework Components tab. Browse to the ActiveX control's .OCX file, make sure its check box is checked in the COM Components tab, and click OK, which adds the ActiveX control to the toolbox. (Alternatively, you can use the ActiveX importing utility, AxImp.exe, which comes with Visual Studio .NET, to import an ActiveX control into .NET this way: AxImp controlname .ocx . After you do, you can add the ActiveX control to the toolbox using the .NET Framework Components tab, not the COM Components tab, in the Customize Toolbox dialog box.) As with much else that motivated .NET, the issue here was security, and it turns out to be lucky that ActiveX controls were made as secure as they were, making it easy to add them to .NET applications.


That's it for our discussion on user controls, which you use in Windows applications. The other available type of user control is the Web user control, which you use in Web applications; they're coming up next.



Microsoft Visual C#. NET 2003 Kick Start
Microsoft Visual C#.NET 2003 Kick Start
ISBN: 0672325470
EAN: 2147483647
Year: 2002
Pages: 181

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