1. Create a login form in asp.net. (See image.)
2. Create table in SQL.
3. Type Asp.Net C# Code in Button Click. (See code)
1. Asp.net Login Page
[Note: LoginId TextBox is: txtlogin.]
[Note: Password TextBox name is: txtpassword.] and
[Note: Login button name is: btnlogin]
2. Create Login Table in SQL server
Create Table UserTable ( UserId varchar(10), Password Varchar(20) )
Insert into UserTable Values('SMITH','12345')
Insert into UserTable values('ANU','5432')
3. Type or copy and paste below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace Login
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnlogin_Click(object sender, EventArgs e)
{
if(txtlogin.Text.Equals(""))
{
lblmsg.Text = "Enter Login Id";
txtlogin.Focus();
lblmsg.BackColor = System.Drawing.Color.Red;
}
else if(txtpassword.Text.Equals(""))
{
lblmsg.Text = "";
lblmsg.Text = "Enter Password";
txtpassword.Focus();
lblmsg.BackColor = System.Drawing.Color.Red;
}
else
{
lblmsg.Text = "";
lblmsg.BackColor = System.Drawing.Color.Wheat;
checkLogin();
}
}
protected void checkLogin()
{
SqlConnection con;
con = new SqlConnection("Server=KOOL-PC;Database=CenterDB;user=sa;password=a;trusted_connection=yes");
SqlCommand cmd = new SqlCommand("Select UserId From UserTable Where UserId=@UserId", con);
cmd.Parameters.Add("@UserId", SqlDbType.VarChar, 10).Value = txtlogin.Text.Trim();
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if(dr.HasRows)
{
CheckUserAndPass();
}
else
{
lblmsg.Text = "";
lblmsg.Text = "User Id does not exist.";
lblmsg.BackColor = System.Drawing.Color.Red;
dr.Dispose();
cmd.Dispose();
con.Close();
}
}
protected void CheckUserAndPass()
{
SqlConnection con;
con = new SqlConnection("Server=KOOL-PC;Database=CenterDB;user=sa;password=a;trusted_connection=yes");
SqlCommand cmd = new SqlCommand("Select UserId,Password From UserTable Where UserId=@UserId And Password=@Password",con);
cmd.Parameters.Add("@UserId", SqlDbType.VarChar, 10).Value = txtlogin.Text.Trim();
cmd.Parameters.Add("@Password", SqlDbType.VarChar, 20).Value = txtpassword.Text.Trim();
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if(dr.HasRows)
{
lblmsg.Text = "Login Success...";
lblmsg.BackColor = System.Drawing.Color.White;
}
else
{
lblmsg.Text = "Login unsuccess";
lblmsg.BackColor = System.Drawing.Color.Red;
}
}
}
}

No comments:
Post a Comment