Run the below SQL script to create database and related table for login process. Also I have included a insert script with dummy admin details.
create database LoginDb
USE LoginDb
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[login](
[user_id] [int] IDENTITY(1,1) NOT NULL,
[username] [nvarchar](50) NULL,
[pwd] [nvarchar](50) NULL,
CONSTRAINT [PK_login] PRIMARY KEY CLUSTERED
(
[user_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
insert into login (username,pwd)values('admin','adminpass123')
Create a ASPX page(login.aspx) with following codes.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %>
<!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>Login page in asp.net c# with sql database</title>
</head>
<body>
<form id="form1" runat="server">
<div align="center">
<fieldset style="width: 200px;">
<legend>Login page </legend>
<asp:TextBox ID="txtusername" placeholder="username" runat="server"
Width="180px"></asp:TextBox>
<br />
<br />
<asp:TextBox ID="txtpassword" placeholder="password" runat="server"
Width="180px" TextMode="Password"></asp:TextBox>
<br />
<br />
<asp:Button ID="btnsubmit" runat="server" Text="Submit"
Width="81px" OnClick="btnsubmit_Click" />
<br />
</fieldset>
</div>
</form>
</body>
</html>
Code Behind source code for login.aspx
using System;
using System.Data;
using System.Data.SqlClient;
public partial class login : System.Web.UI.Page
{
protected void btnsubmit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=LoginDb;Integrated Security = true");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from login where username='" + txtusername.Text + "' and pwd ='" + txtpassword.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Response.Redirect("dashboard.aspx");
}
else
{
Response.Write("<script>alert('Please enter valid Username and Password')</script>");
}
}
}
Create another page dashboard.aspx after successful login
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="dashboard.aspx.cs" Inherits="dashboard" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
This is the dashboard page!!!
</div>
</form>
</body>
</html>
Screenshots are below.
Download Source code
About Author