Answer:
Here’s an ASP.NET Web Forms application that includes:
- A User Control (
LoginControl.ascx
) to accept a username and password. - A Web Form (
Default.aspx
) to use the control and display the validation result.
Steps to Implement
- Create a Web Forms Application in Visual Studio.
- Add a User Control (
LoginControl.ascx
). - Add a Web Form (
Default.aspx
). - Copy the following code into the respective files.
1. Create the User Control (LoginControl.ascx
)
Right-click the project > Add > New Item > Web User Control > Name it LoginControl.ascx
.
LoginControl.ascx
<%@ Control Language="VB" AutoEventWireup="true" CodeBehind="LoginControl.ascx.vb" Inherits="YourNamespace.LoginControl" %>
<table>
<tr>
<td>Username:</td>
<td><asp:TextBox ID="txtUsername" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Password:</td>
<td><asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox></td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label>
</td>
</tr>
</table>
2. Code-Behind for the User Control (LoginControl.ascx.vb
)
Public Class LoginControl
Inherits System.Web.UI.UserControl
Public Event LoginSuccess()
Public Event LoginFailed()
Protected Sub btnLogin_Click(sender As Object, e As EventArgs)
If txtUsername.Text = "DYP" And txtPassword.Text = "Pimpri" Then
lblMessage.Text = "Login Successful!"
lblMessage.ForeColor = System.Drawing.Color.Green
RaiseEvent LoginSuccess()
Else
lblMessage.Text = "Invalid username or password."
lblMessage.ForeColor = System.Drawing.Color.Red
RaiseEvent LoginFailed()
End If
End Sub
End Class
3. Create the Web Form (Default.aspx
)
Right-click the project > Add > New Web Form > Name it Default.aspx
.
Default.aspx
<%@ Page Language="VB" AutoEventWireup="true" CodeBehind="Default.aspx.vb" Inherits="YourNamespace.Default" %>
<%@ Register Src="LoginControl.ascx" TagPrefix="uc" TagName="LoginControl" %>
<!DOCTYPE html>
<html lang="en">
<head runat="server">
<title>Login Page</title>
</head>
<body>
<form id="form1" runat="server">
<uc:LoginControl ID="LoginControl1" runat="server" />
<asp:Label ID="lblResult" runat="server" ForeColor="Blue"></asp:Label>
</form>
</body>
</html>
4. Code-Behind for the Web Form (Default.aspx.vb
)
InPublic Class Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
AddHandler LoginControl1.LoginSuccess, AddressOf Login_Success
AddHandler LoginControl1.LoginFailed, AddressOf Login_Failed
End Sub
Private Sub Login_Success()
lblResult.Text = "Welcome! You are authorized."
End Sub
Private Sub Login_Failed()
lblResult.Text = "Access Denied."
End Sub
End Class