How to Create a Login Form in ASP.NET using SQL Server Database and Visual Studio 2022?[With Source Code]
Login Page in ASP.NET using SQL Database
design code:
-
html code:
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Login Form" Font-Size="XX-Large" Font-Bold="true" ForeColor="#9900CC"></asp:Label>
</div>
<div>
<asp:Label ID="Label2" runat="server" Text="Username:" Font-Bold="true" Font-Size="Larger"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" Height="35px" Width="180px"></asp:TextBox>
</div>
<div>
<asp:Label ID="Label3" runat="server" Text="Password: " Font-Bold="true" Font-Size="Larger"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server" TextMode="Password" Width="180px" Height="35px"></asp:TextBox>
</div>
<input class="checkbox" type="checkbox" onchange="document.getElementById('TextBox2').type=this.checked? 'text': 'password'" />Show Password
<div>
<asp:Button CssClass="btn-login" Font-Size="Large" ID="Button1" runat="server" Text="Login" ForeColor="White" BackColor="#33CC33" Height="40px" Width="90px" OnClick="Button1_Click" />
<asp:Button CssClass="btn-cancel" ID="Button2" runat="server" Font-Size="Large" Text="Cancel" ForeColor="White" BackColor="Red" Height="40px" Width="90px" />
</div>
</form>
</body>
-
style code:
<style>
body{
text-align:center;
margin-top:10rem;
padding-bottom:10px;
}
form{
border:solid;
border-color:mediumpurple;
margin-left:35%;
margin-right:35%;
padding-bottom:10px;
}
div{
padding:5px;
}
.btn-login{
margin-left:15%;
}
.btn-cancel{
margin-left:10px;
}
.checkbox{
margin-left:20%;
font-size:1.5rem;
}
#Label1{
margin-left:12%;
}
</style>
-
backend code:
using System.Data.SqlClient
SqlConnection con = new SqlConnection("Data Source=YOUR-COMPUTER-NAME;Initial Catalog=asplogin;Integrated Security=True;TrustServerCertificate=True");
con.Open();
string loginQuery = "SELECT COUNT(*) FROM login WHERE username=@username AND password=@password";
SqlCommand cmd = new SqlCommand(loginQuery, con);
cmd.Parameters.AddWithValue("@username", TextBox1.Text);
cmd.Parameters.AddWithValue("@password", TextBox2.Text);
int count = (int)cmd.ExecuteScalar();
con.Close();
if (count > 0)
{
Response.Write("<script>alert('login success');</script>");
}
else
{
Response.Write("<script>alert('login error');</script>");
}
Full Video: