How to create,use and manipulate a web user control

User controls are reusable controls that can be defined once and used whenever we need them, in any of the .aspx pages of our application. We do have skins,themes and css to give a standard look to our website. User controls help to achieve that as well because since we define them once and use many times, thus making sure we do not have same controls on pages looking differently. When we make changes to a user control all these changes will be reflected to all instances of the control.

I will try to highlight the following in this post

 

  1. What is a user control and why we need it
  2. How to add Content to a User Control
  3. How to add a User Control to a Web Page
  4. How to define properties in a User Control
  5. How to handle events in a User Control
  6. How to raise events in a User Control
  7. How to access the contents of a User Control

 

We will have to create a simple user control step by step.Imagine you have many pages in your asp.net website. Let's say that you are developing a fully functional e-commerce site. You will find that you need to collect user data, e.g address information (shipping address info,billing address info,registration customer address info). In this example we will use a user control to collect customer address data.

 

We just need Visual Studio 2005/2008 or VS 2010.

1) Launch Visual Studio and create a new asp.net website

2)  Save this website in you local file system and give it a name. Choose C# as your development language for this website

3)  Add new folder to your website and name it UserControl

4) Right-click on this folder and add a new item. From all the items available select a Web User control. Also choose C# as the development language and tick the option Place code in a seperate file.Name the control Address.ascx

5) Switch to the Source view of the Address.ascx control.Have a look at the first line.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Address.ascx.cs" Inherits="UserControls_Items_Address" %>

Notice that even though this directive looks a lot like a page directive it starts with  @ Control

6)  Open the Address.ascx.cs file.Your newly create class does not inherit from the System.Web.UI.Page but from

public partial class UserControl_Address : System.Web.UI.UserControl

The classes System.Web.UI.Page and System.Web.UI.UserControl have lots in common since they both inherit from another class,TemplateControl class

For more information click here

7)  Let's work on our new user control. Insert a table in your "Address.ascx" page. This table should have 4 rows and 2 columns.

8)  Add 4 label web server controls on the first 4 rows of the first column. Set their ID property as you like(AddressLabel1,AddressLabel2,AddressLabel3,PostCodeLabel). Set their text property like  this

  • Address1
  • Address2
  • Address3
  • PostCode

9) Add 4 textbox web server controls on the 4 rows of the second column.Set their ID property like this

txtaddr1,txtaddr2,txtaddr3,txtpostcode

10)  In order to add this newly created web user control to the Default.aspx page just drag and drop it from the Solution Explorer onto the .aspx page

11) Look in the source view of the Default.aspx page and notice this line

<%@ Register src="UserControl/Address.ascx" tagname="Address" tagprefix="uc1" %>

This is how the user control is registered with the .aspx page. You will also see this

<uc1:Address ID="Address1" runat="server" />

Change the ID property to Shipping_Address

 12) We can add new server controls to our user control. If we wanted to have a label control as a header we must select the Address.ascx and just above the table to insert a new label.Name this label headingLabel.

One can set the Text property of this new header label control and make it apparent to the end use that we talk about Shipping Address. But as I mentioned before we need to use this user control in many places in our website. So we do not want to have a fixed Text property but one we can set its value accordingly.

Select the Default.aspx page and in the

 <uc1:Address ID="Shipping_Address"  runat="server"/> section you will see that headingLabel is not exposed as a property. It cannot be accessed from our page.

 

So we must add a new public property on this UserControl_Address class.This is the same with every other normal class.

So in the Address.ascx.cs file type

 

 public string Header
    {
        set { headingLabel.Text = value; }
    }

 

13) Now you can go back to the Default.aspx page (Source View) and add the Header=Shipping Address <uc1:Address ID="Shipping_Address"  runat="server" Header="Shipping Address">

14) It is very easy to handle events in a user control.Add a button to the user control. This means that you go to the Address.ascx file and drop a button under the table. Set the ID property to be txtNext and the Text property to be Next. Add another .aspx page to your website and call it Checkout.aspx. Double click on the button and you have the empty event handling routine.

Type the following

 protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Checkout.aspx");
    }

 You see how easy it is to handle events in a user control.

 14 ) Let's see now, how we can create an event in the user control. First we need to define an event.

When we define an event we must define the signature of the event handler method. We do that by choosing a delegate type.We also must give a name to our event. We will call it Confirmed event.


Select the Address.ascx.cs  and type

public event EndEventHandler Confirmed

So we know now that our user control class will raise an event and we must write some code to actually cause this event to be raised.

So in our Button_Click event handler, we type

if (Confirmed!=null) Confirmed(this, new EventArgs());

When the user clicks the button, the Confirmed event will be raised.

Select the Default.aspx page and in the Source View locate the

<uc1:Address ID="Shipping_Address"  runat="server" Header="Shipping Address"/>

and change it to 

<uc1:Address ID="Shipping_Address" onConfirmed="ShippingAdress_Confirmed"  runat="server" Header="Shipping Address"/>

We just added the event handler in the user control.We do that by entering the name of the event and the name of the event handling routine we will add shortly.

In order to add the ShippingAdress_Confirmed event handling routine we go back to the Default.aspx.cs file and type

protected void ShippingAdress_Confirmed(object sender, EventArgs e)
    {
      
       
    

    }

Inside this routine add this line of code:

Response.Write("The event has been handled");

Run the application and you will see the event raised and handled (the text "The event has been handled" will be printed in the Default.aspx page)

For more information on events have a look here .

15) Let's assume that we need 2 instances of our user contol in the Default.aspx page (e.g one for shipping address and one for billing address).Select the Default.aspx and add a new user control. Go to the Source View and add a Header property e.g Billing Address. Also set the ID property to "Billing_Address". You should have something like this

 <uc1:Address ID="Billing_Address" runat="server" Header="Billing Address" />.

Run the application and see the 2 user controls.

We need to copy all the fields entered in our Shipping address to the Billing address fields.

So we must access the text properties of the Shipping_Address user control and copy them to the Billing_Address user control.

You will see that it is impossible to access these textbox values directly  from ShippingAdress_Confirmed event handler in the Default.aspx.cs class, because these text properties are protected and thus invisible to the event handling routine.

So we need to create some public properties in our user control class.

Select the Address.asx.cs file and type

 

 public string Address1
    {
        get {return txtaddr1.Text; }
        set {txtaddr1.Text=value;}
    }
    public string Address2
    {
        get { return txtaddr2.Text; }
        set { txtaddr2.Text = value; }
    }
    public string Address3
    {
        get { return txtaddr3.Text; }
        set { txtaddr3.Text = value; }
    }
    public string PostCode
    {
        get { return txtpostcode.Text; }
        set { txtpostcode.Text = value; }
    }

 16) Select the Default.aspx.cs file and inside the ShippingAddress_Confirmed event handling routine, comment out the ( Response.Write("The event has been handled");) and type

 
        Billing_Address.Address1 = Shipping_Address.Address1;
        Billing_Address.Address2 = Shipping_Address.Address2;
        Billing_Address.Address3 = Shipping_Address.Address3;
        Billing_Address.PostCode = Shipping_Address.PostCode;

Run your application. Type some address data into the first user control and then click the button.You will see the entered data copied in the second user control.

Hope it helps. If you need the source code just email me.

4 Comments

Comments have been disabled for this content.