User Controls
The composition of a user control is very simple and requires a smaller skill set than that required by custom control developers
. User controls preserve the use of ASP.NET mark-up coupled with the code behind model (although inline code is an option).
One of the great things about user controls is that they allow a quick conversion from something like an existing ASP.NET page to a user control - and as a result they have many similarities. Some of the similarities include the use of existing server controls that ASP.NET offers, as well as the event model that you are familiar with as ASP.NET developers. User controls provide a quick and easy way to introduce modularity into an ASP.NET web application.
User controls - unlike ASP.NET pages that have the file extension .aspx - have the extension .ascx. User controls files cannot be requested via a browser; they can only be used via the containing ASP.NET page. Web servers like IIS and Cassini prohibit browsing to files with the .ascx file extension.
Like ASP.NET pages - in the context of a file based web site - compilation of a user control is done upon first request.
So why after this glowing review should we even care about custom control development in ASP.NET? Custom controls allow us a more atomic control on authoring, as well as the ability to ship our controls as a dynamic link library (.dll) which can be pre-compiled as well as integrating nicely with the Visual Studio IDE.
If you are building controls specifically for a certain web application, then user controls will probably be all you need. However, if your desire is to build redistributable controls that integrate well with the Visual Studio IDE, then custom controls are the best choice.
User Control example
Even if the main purpose of this article is covering custom controls, I would like to start with a walkthrough about the creation of a simple user control.
In the following example, I have identified a component that will appear many times within my hypothetical web site. The user control that we will create simply consists of a GridView and a SqlDataSource that queries for all the ContactName's and CompanyName's from the Northwind Customers table.
When creating user controls I like to create a new folder within my web site entitled... yes you guessed it, UserControls; and drop all my user controls into that folder. However, this isn't a requirement.
Step 1: Adding a user control to the web site
Adding a user control to your solution is real simple. You just have to right click your solution and click Add New Item; then from the dialog window click Web User Control and name the control MyUserControl.ascx.
Figure 1: Adding a Web User Control
Step 2: Adding the ASP.NET controls to MyUserControl.ascx
As mentioned earlier this user control will merely consist of a GridView and a SqlDataSource ASP.NET server controls.
Before we go ahead and add our controls to the user control, notice that the Page directive is not used for our user control, and that it has been replaced with the Control directive.
Listing 1: Control directive
view sourceprint?
1.<%@ Control Language="C#"
2. AutoEventWireup="true" CodeFile="MyUserControl.ascx.cs"
3. Inherits="UserControls_MyUserControl" %>
As well as the Control directive also note that our code behind derives from the System.Web.UI.UserControl class and not from System.Web.UI.Page.
Listing 2: Deriving from the UserControl class
view sourceprint?
1.public partial class UserControls_MyUserControl : System.Web.UI.UserControl
There is only one similarity between the System.Web.UI.UserControl and System.Web.UI.Page types: they both derive from TemplateControl.
Let's go ahead and add the required server controls to our user control.
Listing 3: Adding a GridView and SqlDataSource server control to our user control
view sourceprint?
Listing 1-1 shows the final version of MyUserControl.ascx.
Step 3: Adding our user control to a Web Form
There are a few ways in which we can do this. We can either use the Register directive, or we can go ahead and register our user control in the web.config.
Using the Register directive is really simple and allows all web forms with the appropriate Register directive to go ahead and use our user control. Setting up the Register directive is easy. We need to provide a TagPrefix, TagName and Src for the user control – all of which are attributes of the Register directive.
Listing 4: Setting up the Register directive
view sourceprint?
1.<%@ Register TagPrefix="gb" TagName="Customers"
2. src="~/UserControls/MyUserControl.ascx" %>
As well as using the Register directive, as of ASP.NET 2.0, we can go ahead and register our user control within the controls element of the pages element.
Listing 5: Registering our use control in the web.config
view sourceprint?
When registering our user control in the web.config file, all pages within the web site can now use the user control omitting the Register directive.
Step 4: Using our simple user control within a Web Form
This is really simple. Either setup the Register directive on your Web Form or register your user control within the web.config as shown in step 3. With that done, you will be able to use your control as shown in the following listing.
Listing 6: Using our user control within a Web Form
view sourceprint?
There are a few things to remember about user controls. The first is that you shouldn't include a server form element, which is a form control with the runat="server" attribute. However, you can use a standard form element. Also, you should not include any HTML elements that are already contained in the Web Form, like body, head and so on. If you require either, a MasterPage might be better suited for your needs.
Figure 2: Our simple user control in action
Custom Controls
The power of custom controls is staggering. You can create highly complex controls and then bundle them up and ship them as compiled managed .dlls. As I mentioned before, custom controls can provide a richer interface between the developer and the control, via the Visual Studio IDE. This is achieved using attributes to decorate various parts of a custom controls internals.
When creating a custom control, we derive our control class from one of two base types:
• System.Web.UI.Control
• System.Web.UI.WebControl
Control
Deriving from the Control class allows our control to take advantage of the rendering methods provided by the Control class, as well as the use of ViewState.
WebControl
The WebControl class derives from the Control class. However, if we derive our custom control from WebControl, we get free support for many visual aspects of our control, like font size, CSS classes, background colour and so on.
Which class should I derive from?
When you are creating a custom control that requires little or no UI, then you should derive from the Control class. If your control does require the need for extensive UI support, then you should derive from WebControl.
Creating a simple custom control
In this first part of the series we will create a trivial Label-like control that simply allows the user to define the text of a server control. This control will derive from the Control class.
Step 1: Creating a new Web Control Library project
Right click on your web site solution and click on the Add New Project. From the dialog window, choose the Web Control Library project template. You can name this project whatever you want.
Figure 3: Creating a new Web Control Library project
Step 2: Deriving from the Control class
Go ahead and add a new class to your Web Control Library called SimpleLabel, and derive SimpleLabel from the System.Web.UI.Control class.
Listing 7: Deriving from Control
view sourceprint?
01.using System;
02.using System.Web.UI;
03.
04.namespace Org.GBarnett.Dns.WebControls
05.{
06. public class SimpleLabel : Control
07. {
08. }
09.}
Step 3: Adding some functionality to our control
In this step we will override the Render method defined in the Control class, and also add a Text property to the class so that our user can define the text of our label.
First, we will add the Text property to our class and store the value in ViewState so the control can maintain state over post back.
Note: ViewState will be described in detail in the next part of this series.
Listing 8: Text property
view sourceprint?
01.public string Text
02.{
03. get
04. {
05. string s = ViewState["Text"] as string;
06. return (s == null) ? string.Empty : s;
07. }
08. set
09. {
10. ViewState["Text"] = value;
11. }
12.}
Now we will go ahead and override the Render method of our control.
Listing 9: Overriding the Render method
view sourceprint?
1.protected override void Render(HtmlTextWriter writer)
2.{
3. writer.RenderBeginTag(HtmlTextWriterTag.Span);
4. writer.Write(Text);
5. writer.RenderEndTag();
6.}
In the previous listing, we start off by writing an opening tag, then writing out the user defined text and then finally closing that opening tag.
Note: We will discuss the control lifecycle in the next part along with rendering.
Listing 10: Our final control
view sourceprint?
01.using System;
02.using System.Web.UI;
03.
04.namespace Org.GBarnett.Dns.WebControls
05.{
06. public class SimpleLabel : Control
07. {
08.
09. public string Text
10. {
11. get
12. {
13. string s = ViewState["Text"] as string;
14. return (s == null) ? string.Empty : s;
15. }
16. set
17. {
18. ViewState["Text"] = value;
19. }
20. }
21.
22. protected override void Render(HtmlTextWriter writer)
23. {
24. writer.RenderBeginTag(HtmlTextWriterTag.Span);
25. writer.Write(Text);
26. writer.RenderEndTag();
27. }
28. }
29.}
Please go ahead now and build the project.
Step 4: Using the SimpleLabel custom control within an ASP.NET project
You have two choices here: Either install the resulting .dll into the global assembly cache (GAC) or drop the .dll into the bin folder of your web application. We will do the latter.
Right click on your web site solution and click Add Reference, a dialog window will appear. Click on the Browse tab and then browse to the resulting .dll created from the web control library project.
Figure 4: Referencing our web control library project
With the .dll reference you can either use the Control directive to register your custom controls, or you can use the web.config file to do so. I will use the web.config to register my control. If you want to use the Control directive please check the beginning of this article.
Listing 11: Registering the web control library
view sourceprint?
1.
2.
3.
5.
6.
With our control library registered we can now go ahead and use it!
Listing 12: Using our control within a Web Form
view sourceprint?
Figure 5: Our custom control in all of its glory
If you view the source of the resulting HTML then you will see that Granville is a child of the element, which is how we defined our control in the Render method.
Adding custom control to toolbox.
Step 1 – Switch over to the web project in which you want to use the control.
Step 2 – In toolbox add your own tab or click on general tab.
Step 3 – Right click in the selected tab area and click Chose Items.
Step 4 – This will open Choose Toolbox Item screen. Click on Browse button and specify the path of dll you created in your myControlLib project.
Step 5 – Click Ok and you’re done. Your Custom control will be added to the toolbox as shown below.
Difference between User Control and custom control:
User control
1) Reusability web page
2) We can’t add to toolbox
3) Just drag and drop from solution explorer to page (aspx)
4) U can register user control to. Aspx page by Register tag
5) A separate copy of the control is required in each application
6) Good for static layout
7) Easier to create
8)Not complied into DLL
9) Here page (user page) can be converted as control then
We can use as control in aspx
Custom controls
1) Reusability of control (or extend functionalities of existing control)
2) We can add toolbox
3) Just drag and drop from toolbox
4) U can register user control to. Aspx page by Register tag
5) A single copy of the control is required in each application
6) Good for dynamics layout
7) Hard to create
8) Compiled in to dll
No comments:
Post a Comment