User Control In ASP.NET

The name defines itself: user control. The user can design his or her own control with a group of control. Afterwards we can useit anywhere in theapplication. We can use user control for displaying data and data entry forms.

A user control is stored in a separate file ASCX file extension.

User Control means collection and uses and combination of several ASP.NET controls. If your project requires any functionality reused on multiple pages, then code handling and maintenance become quite easy with user control.

User Control does not have <html>, <body> and <form> tag. User control is embedded within page.

User control is the concept of reusability; in shorta developing element that can be used in multiple places within a web application or web site.

User control has its own events, similar to a web page event.

Concept of user control is to create it one time and use n number of times withinthe   application. 

Step by Step creating a User Control

  1. Create a WebSite Project.

    File-> New->WebSite.

    WebSite

    Some examples or scenarios where we can use user control.

    • In Leave web Application create a user control for displaying Leave balance.
    • In E-commerce site or Shopping application create a user control for displaying  Detailed Cart Information.
    • In Club Member web application create a user control to display member.

  2. Create a new WebForm.

    Right click on project Click ADD, then Add New Item.

    Create a new WebForm

  3. Create a new User Control.

    Right click on project click ADD -> Add New Item.

    Add New Item

  4. We had created a two file Default.aspx WEBFORM and FriendWebUserControl.ascx USER CONTROL.

    USER CONTROL

  5. Double Click on DEFAULT.ASPX file.

    Drag N Drop GridView Control from ToolBox.

    GRIDVIEW
    1. <asp:GridView ID="gvFriend" runat="server" AutoGenerateColumns="False">  
    2.     <Columns>  
    3.         <asp:BoundField DataField="FriendID" HeaderText="Friend ID" />  
    4.         <asp:BoundField DataField="FriendName" HeaderText="Friend Name" />  
    5.         <asp:ButtonField Text="View Detail" /> 
    6.     </Columns>  
    7. </asp:GridView>  
  6. I had added Three Fields:

    1. To display Friend ID
    2. To display Firend Name
    3. Button to View Friend Detail

    In design view GRIDVIEW display like this.

    design

    To apply auto format style on GRIDVIEW, click on Black color marked button called SMART TAG.

    auto format

    I had selected BROWSUGAR category. After selection GRIDVIEW displays like this.

    BROWSUGAR category

    Till Now Your code behind file code of DEFAULT.ASPX:

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Configuration;  
    4. using System.Data;  
    5. using System.Data.SqlClient;  
    6. using System.Linq;  
    7. using System.Web;  
    8. using System.Web.UI;  
    9. using System.Web.UI.WebControls;  
    10. public partial class _Default: System.Web.UI.Page  
    11. {  
    12.     string ConStr = ConfigurationManager.ConnectionStrings["MemberCDACConnectionString"].ConnectionString;  
    13.     protected void Page_Load(object sender, EventArgs e)  
    14.         {  
    15.             if (!IsPostBack)  
    16.             {  
    17.                 BindRepeater();  
    18.             }  
    19.         }  
    20.         /// <summary>   
    21.         /// To load data into Repeater control   
    22.         /// </summary>   
    23.     public void BindRepeater()  
    24.     {  
    25.         SqlConnection con = new SqlConnection(ConStr);  
    26.         SqlDataAdapter da = new SqlDataAdapter("Select * From tblFriends", ConStr);  
    27.         DataSet ds = new DataSet();  
    28.         da.Fill(ds, "FriendsTable");  
    29.         gvFriend.DataSource = ds;  
    30.         gvFriend.DataBind();  
    31.     }  
    32. }  
    run

     

  7. Now, double click FriendWebUserControl.ascx user control to work on.

  8. FriendWebUserControl.ascx file we can attach to any ASPX and utilize the full power of User Control.

    In user control, we will create public property on that basis User Control will display particular friend details.

    In User Control ASCX code, I had used a Repeater Control, Inside repeater control displayed Friend Details.

    CODE OF FriendWebUserControl.ascx:
    1. <%@ Control Language="C#" AutoEventWireup="true" CodeFile="FriendWebUserControl.ascx.cs" Inherits="FriendWebUserControl" EnableViewState="True" %>  
    2.     <h3><u>Friend Detail From User Control</u></h3>  
    3.     <asp:Repeater ID="rptFriend" runat="server">  
    4.         <HeaderTemplate> </HeaderTemplate>  
    5.         <ItemTemplate>  
    6.             <table border="1" style="border-color:darkorange;background-color:lightgray">  
    7.                 <tr>  
    8.                     <td><b>Friend ID :</b>  
    9.                         <asp:Label ID="lblFriendID" runat="server" Text='<%# Eval("FriendID") %>'></asp:Label>  
    10.                     </td>  
    11.                 </tr>  
    12.                 <tr>  
    13.                     <td><b>Friend Name :</b>  
    14.                         <asp:Label ID="lblFriendName" runat="server" Text='<%# Eval("FriendName") %>'></asp:Label>  
    15.                     </td>  
    16.                 </tr>  
    17.                 <tr>  
    18.                     <td><b>Place :</b>  
    19.                         <asp:Label ID="lblPlace" runat="server" Text='<%# Eval("Place") %>'></asp:Label>  
    20.                     </td>  
    21.                 </tr>  
    22.                 <tr>  
    23.                     <td><b>Mobile :</b>  
    24.                         <asp:Label ID="lblMobile" runat="server" Text='<%# Eval("Mobile") %>'></asp:Label>  
    25.                     </td>  
    26.                 </tr>  
    27.                 <tr>  
    28.                     <td><b>Email ID :</b>  
    29.                         <asp:Label ID="lblEmailID" runat="server" Text='<%# Eval("EmailAddress") %>'></asp:Label>  
    30.                     </td>  
    31.                 </tr>  
    32.             </table>  
    33.         </ItemTemplate>  
    34.         <FooterTemplate> </FooterTemplate>  
    35.     </asp:Repeater> <br /> <br /> <a href="Default.aspx">Back To Main Page</a>  
    In User Control ASCX.CS code is used and created in the following ways:

    1. Created a FriendID property: Which receiving a value of Selected FriendID from GridView.

    2. Created a BindRepeater method: Which fetches data from Database and hands over to Repeater control.

    CODE of FriendWebUserControl.ascx.cs:

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Configuration;  
    4. using System.Data;  
    5. using System.Data.SqlClient;  
    6. using System.Linq;  
    7. using System.Web;  
    8. using System.Web.UI;  
    9. using System.Web.UI.WebControls;  
    10. public partial class FriendWebUserControl: System.Web.UI.UserControl  
    11. {  
    12.     string ConStr = ConfigurationManager.ConnectionStrings["MemberCDACConnectionString"].ConnectionString;  
    13.     public int FriendID  
    14.     {  
    15.         get;  
    16.         set;  
    17.     }  
    18.     protected void Page_Load(object sender, EventArgs e)  
    19.         {  
    20.             BindRepeater(FriendID);  
    21.         }  
    22.         /// <summary>   
    23.         /// To load data into Repeater control   
    24.         /// </summary>   
    25.     public void BindRepeater(int SelectedFriendID)  
    26.     {  
    27.         SqlConnection con = new SqlConnection(ConStr);  
    28.         SqlDataAdapter da = new SqlDataAdapter("Select * From tblFriends where FriendID = " + SelectedFriendID, ConStr);  
    29.         DataSet ds = new DataSet();  
    30.         da.Fill(ds, "FriendsTable");  
    31.         rptFriend.DataSource = ds;  
    32.         rptFriend.DataBind();  
    33.     }  
    34. }  

     

  9. I will use usercontrol in another ASPX page.

  10. Right click on project and add new WebForm.

    WebForm

    DisplayFriendDetail.aspx

  11. Double Click on DisplayFriendDetail.aspx page.

  12. How to use User Control?

    The following are the ways:

    a. Register the UserControl at the top the ASPX.
    b. UserControl on the Page.

    Otherwise:

    Drag n Drop the User control on ASPX page.
  13. Run Application.

    Output

    Run Application

    Output

Interview questions related to this article.

  1. What is a User Control?
  2. How to use User Control (Ascx) in web page.
  3. True / False : User control having <body>, <form>.
Read more articles on ASP.NET:


Similar Articles