How to create User Control in ASP.Net


User control is powerful functionality of ASP.NET. With the help of the user control you can reuse the Design as well as code in the application. Developing User control is similar to developing form in ASP.NET. User control is created in markup file with .ascx extension.

We create two user control one for collect the user information and second for Display the user information.

Step 1:  Add the Web user control in your form with the name UserInformation.ascx and UserInformationGrid.ascx.

1.gif

Step 2:  Add the code in Userinformation.ascx

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

<table align="center">
    <tr>
        <td colspan="2">
            <asp:Label ID="lblusername" runat="server" ForeColor="Red"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            UserName:
        </td>
        <td>
            <asp:TextBox ID="txtusername" runat="server"></asp:TextBox><asp:RequiredFieldValidator
                ID="RequiredFieldValidator1" runat="server"
                ControlToValidate="txtusername">*</asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
        <td>
            <asp:Button ID="btnSaveName" runat="server" Text="Save"
                OnClick="btnSaveName_Click" style="height: 26px" />
        </td>
    </tr>
</table>

In Userinformation.ascx.cs file add the code like this.

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Linq;

public partial class UserControl_UserInformation : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
        }
    }
    protected void btnSaveName_Click(object sender, EventArgs e)
    {       
        InsertData();
        Response.Redirect("~/Default.aspx");
    
    private void InsertData()
    {
        Userinfo info = new Userinfo();
        info.UserName = txtusername.Text.Trim();
        using (UserInformationDataContext db = new UserInformationDataContext())
        {
            try
            {
                db.Userinfos.InsertOnSubmit(info);
                db.SubmitChanges();
            }
            catch (Exception ex)
            {
                Response.Write("Error:" + ex.Message);
            }
        }
    }
}

Step 3:   Add the code in UserInformationGrid.ascx.

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

<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
    AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="ID" HeaderText="ID" />
        <asp:BoundField DataField="UserName" HeaderText="UserName" />
    </Columns>

</asp:GridView>

UserInformationGrid.ascx.cs add

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Linq; 

public partial class UserControl_UserInformationGrid : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            using(UserInformationDataContext db = new UserInformationDataContext())
            {
                var info = from p in db.Userinfos
                           select new {
                               p.ID,
                               p.UserName               
                           }; 
                if (info != null)
                {
                    GridView1.DataSource = info;
                    GridView1.DataBind();
                }
            }
        }
    }
}

Step 4: To add the user control in your page you must add tag

<%@ Register%> . it contain src,TagName,TagPrefix

Your code in the your aspx file like this.

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register src="~/UserControl/UserInformation.ascx" TagName="UserInformation" TagPrefix="UserInformation" %>
<%@ Register src="UserControl/UserInformationGrid.ascx" tagname="UserInformationGrid" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td valign="top"> 
                <UserInformation:UserInformation id="UserInformation" runat="server"/>                                     
                </td>
                <td>
                    <uc1:UserInformationGrid ID="UserInformationGrid1" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:PlaceHolder ID="_placeHoldaer" runat="server"></asp:PlaceHolder>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Step 5: Build the application and run the project.

2.gif

Conclusion:

In this article we have seen how to create user control and how to use it in our web forms.

erver'>
Up Next
    Ebook Download
    View all
    Learn
    View all