Creating user controls in ASP .Net by azamsharp

Introduction:

User controls is a new feature that is added in Asp.net. For those who are familiar with the classic asp programming you will find user controls acting much like the include files. The main purpose of the user control is to divide the parts of the pages which are being used on many pages. In this article I will show you how you can make your own user control and perform different actions on it.

Page not using a User Control

Let’s see a page that is not using a user control. Now as you go from one page to another you will see that each page has a footer menu which contains different options. For those of you who don’t know what I am talking about please see the image below:

All the options you see are just basic html and this is not a user control. So, what do you think the problems will be. As you have already guessed if I make a small change in any of the options you see above like if I go and add a new blog with title “Java Script” than I need to go to each and every page and edit the html file and manually make the change.
This will be a total chaos if your website has many pages. That’s why the footer menu you see above should be a user control instead of plain html embedded on each page. If it was user control I just need to change it at one location and that’s it. It will automatically change on all of the pages since all the pages will contain the same user control.

Making a simple user control:

Let’s see how we can make a simple user control. First make a simple asp.net web application than on the solution right click and add a Web User Control. You will see a blank screen where you can add user controls and text. I have just added “This is my Header control”. Your simple user control will look something like this:

If you see the source code of this user control if will be something like the image below:

You will notice that the user control html code does not contain the page directive. That’s because it’s not a page it’s a user control and that’s why it contains the Control directive instead of page. Also you will note that it does not matter how many controls you add to the user control. By adding controls I mean you can add TextBox, Label all the controls in the textbox it will never have a form tag.
One page can have only one form tag and since the webform already has one form tag that’s why you cannot have a form tag in the user control.

Putting the user control on the page:

Let’s see how we can put the user control on the page. There are many ways of loading a user control on the page. The simplest approach is to just drag and drop the user control on the page. When you drag and drop the user control on the page a registor directive is automantically added to the page which denotes that the User Control has been registered on this page.
Here is the screen shot of what the web form html look like when you have dragged and dropped the User Control on it.

And as you can see in the image the user control has been added to the page and the registor directive is written in the html code of the webform.
This was one of the ways of loading the user control on your page. Remember that you can also manually add the registor directive and add the user control on any page.
Let’s see how we can load the user control programmatically.
In order to add the user control programmatically we need to notify the webform that we are going to do that. For that we include the reference directive at the top of the webform on which we wish to load the user control.
<%@ Reference Control = “Header.ascx” %>
Next we need to do some coding to load the user control on the page. First place a placeholder control so that you can load the user control on that place holder control.

private void Page_Load(object sender, System.EventArgs e)
{
	if(!Page.IsPostBack)
	{
		Header uc = (Header) Page.LoadControl("Header.ascx");
		PlaceHolder1.Controls.Add(uc);
	}
}

As you see that loading a user control is also fairly simple and straight forward. We Loaded the control using the Page LoadControl method and we did some casting and finally added the control in the place holder for display.

These all were fairly common operations of the user control let’s see few more things we can do using user controls.

Passing Values from User Controls on the form:

Suppose you have a user control that has a textbox and you need to pass the value from that textbox and display it on the page. Let’s see how we can do that. In this case our user control will consist of a textbox and a button and we will transfer some name from the textbox to the page on the button click event. You can see the user control as it appear in the image below.

The UserControl used for this example is: UserControlTextBox.ascx and the webform used is TextBoxTester.aspx.

Let’s see the code behind file for the User Control Button click event:

void Button1_Click(object sender, System.EventArgs e)
{
  // Simply sends the contents of the textbox to the page 
  Response.Redirect("TextBoxTester.aspx?Name="+txtName.Text);

}

As you see when the button is clicked we simply sends the data from the user control to the page just like we were passing the data between pages.

Let’s see the code where the page receives the name from the user control and prints it on the page.

private void Page_Load(object sender, System.EventArgs e)
{

	if(!Page.IsPostBack)
	{
		if(Request.QueryString["Name"] != null)
		{
			string name = Request.QueryString["Name"].ToString();
			Response.Write(name);
		}
	}
}

In the above code the page request and receives the query string and finally prints the name on the screen.

So, what’s the purpose of showing you all this code you already know this right? Well the point I was making is that user controls and page are very similar in action even page is also a control. So transferring values from the user control to the page is same as transferring values from one page to another.

Let’s see some thing different. We have a user control which has one TextBox and that’s it. Now the user clicks the button which is on the webform and the value of the TextBox is printed on the screen.

Accessing value of a web server control in User control:

We will be using following files in this example:

UserControl File: SingleTextBox.ascx

WebForm File: TesterSingleTextBox.aspx

The User Control “SingleTextBox.ascx” will only contain a single textbox. So, let’s see how we implement the TesterSingleTextBox.aspx page so that if will extract the value from the TextBox contained in the user control.

Here is the code you need to implement in the User control.

	if(!Page.IsPostBack)
	{ 
		private void Page_Load(object sender, System.EventArgs e)
		{
		}
	}

	public string Text
	{
		get { return txtName.Text; }
		set { txtName.Text = value; }
	}

As you see we have exposed the property which returns or set the value of the TextBox. Let’s see the code that will be used on the Aspx page to extract or to set the value of the TextBox.

private void Page_Load(object sender, System.EventArgs e)
{
	if(!Page.IsPostBack)
	{
		SingleTextBox s = new SingleTextBox();
		s.Text = "aaa"; // sets the value 
		Response.Write(s.Text); // writes the value
	}
}

I hope you liked the article happy coding !

Attachments:

Project Files: UserControls_azam.zip

About the Author:

Mohammad Azam is currently completing his bachelors in Computer Science from University of Houston. Mohammad Azam is always seeking freelance projects to work. Currently he is also seeking Summer 2005 Internship. If any one interested or have further questions you can contact him at azamsharp@gmail.com.