Introduction:

In this article we will learn how to create UserControl in asp.net or why use user controls in asp.net or what is user controls in asp.net with example.

Description:

In software development, every developer or programmer wants to reusability of the code. In asp.net web form UserControl provide reusability of code to the developer. For example we need to Login Form in many places in my application. In this situation we create a usercontrol and use it everywhere, whenever we required.

Let’s see how to create user control:

Go to solution explorer, Select your Project  (Demo) , Now create a folder UserControls and then Right Click on UserControls folder see below fig.



When you click New Item then open a popup window see below fig.


Now select web User Control and Give your Control Name like (_Login.ascx) then click to add button.

After clicking add button your user control created in your  UserContros Folder let’s See below Fig.



Now double click on _Login.ascx User control and design your login UI. Let’s see below.

_Login.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="_Login.ascx.cs"
Inherits="Demo.UserControls._Login" %>
<table>
    <tr>
      <td colspan="2" style="text-align:center;"><b>Login</b></td>        
    </tr>
     <tr>
        <td>UserID:</td>
        <td>
            <asp:TextBox ID="txtUserID" runat="server" Width="120px">
      </asp:TextBox></td>
    </tr>
     <tr>
        <td>Password:</td>
        <td>
         <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" Width="120px">
     
    </asp:TextBox></td>
    </tr>
     <tr>
        <td></td>
        <td>
    <asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" /></td>
    </tr>
</table>

Now you can write Login Logic on Login Button Click event Let’s See Below:

_Login.ascx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace Demo.UserControls
{
    public partial class _Login : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
 
        }
 
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            var userID = txtUserID.Text;
            var password = txtPassword.Text;
            Login(userID, password);
        }
 
        public void Login(string UserID, string Password)
        {
            //you may write user Login Logic here.
            Response.Redirect("Home.aspx", false);
        }
    }
}

When you use it and click on login button your login will success and redirect to Home.aspx page.

 Output:



0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

Welcome to SQL Tutorials Point

Don't have an account? Click here to Create a new account, it takes less than a minute.