Creating User Controls using ASP.NET

In this we see what is user control. how can we create a user control and how we add it in our website's page and use it in ASP.NET.

User Control in ASP.NET

Whenever we want to create a static content and standard layouts within number of pages we can use user control.
It enables a part of ASP.NET page to be reused. The reusable part is in form of a control with the extension .ascx

Steps to create a User control in ASP.NET:

a. Create a new website in that add a new item(user control).
b. Do the designing as we do in web page.
c. Write the necessary codes.

Consider an example:
In this we create a user control Joiningdate.ascx
In this we take 1 label, 1 textbox, 1 button and a calender control.

Now we write the code to show selected date in the textbox.

protected void Page_Load(object sender, EventArgs e)
Calendar1.Visible = false;

protected void Button1_Click(object sender, EventArgs e)
Calendar1.Visible = true ;

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
TextBox1.Text = Calendar1.SelectedDate.ToShortDateString();
Calendar1.Visible = false;

On button click calender is visible we select the date and display in textbox.

Now we have to use it in out web page.

Steps to add User control in ASP.NET webpage:

a. Register the control on the webpage.
b. Then we can add it to any location we want in the page.

//code to register the usercontrol in our webpage:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Src="~/DOB.ascx" TagName ="DOB" TagPrefix ="asp" %>

Src is the location of user control
TagName and TagPrefix is given by us. Whwtever we want.

we add it in any row or column like
<asp:DOB ID ="DOB1" runat ="server" /> 

asp is the TagPrefix and DOB is the TagName.


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: