Login Form with Database in ASP.NET
Login.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="MyFirstProgram.Login" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<div class="row">
<div class="col-lg-8">
<h4>Login Form</h4>
<hr />
UserName:<asp:TextBox ID="txtusername" runat="server" CssClass="form-control"></asp:TextBox><br />
Password:<asp:TextBox ID="txtpassword" CssClass="form-control" TextMode="Password" runat="server"></asp:TextBox><br />
<asp:Button ID="btnLogin" CssClass="btn btn-primary" runat="server" Text="Login" OnClick="btnLogin_Click" />
</div>
</div>
</div>
</form>
</body>
</html>
Login.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace MyFirstProgram
{
public partial class Login : System.Web.UI.Page
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Select * from users where username=@user and password=@pass";
con.Open();
cmd.Parameters.AddWithValue("@user", txtusername.Text);
cmd.Parameters.AddWithValue("@pass", txtpassword.Text);
SqlDataReader rd = cmd.ExecuteReader();
if(rd.HasRows)
{
Response.Redirect("Dashboard.aspx");
}
else
{
Response.Write("Invalid username or password");
}
con.Close();
}
}
}
Comments
Post a Comment