First of all we have to design a table in
database in order to store the user and password of the entire user who can log
on to our application having at least two entities ‘username’ and ‘password’ ,
here my database name is ‘Employee’ and table name is ‘login’.
Our next step is to design login form.

Set the password text box ‘password char’ to
‘*’.
Now, once the login form and tables are designed
our next step is to design the code for the login form.
Coding
Boolean log = false;
//Assigning public variable log of type Boolean to set property of this from
//in order to access it from other form.
public Login()
{
InitializeComponent();
}
private void btnCancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
//Application will exit if cancel button is clicked.
public void fnlogin()
{
//Function for login
try
{
//Managing connection to the database
string sqlString = "Server=abc\\SQLEXPRESs;Database=Employee;Trusted_Connection=True";
SqlConnection con = new SqlConnection(sqlString);
con.Open();
SqlCommand cmd = new SqlCommand("select UserName, Password from login whereUserName='" + txtUserName.Text.Trim() + "' and Password='" + txtPassword.Text.Trim() + "'", con);
//Fetching only those records from the table which matches with the record
//in the text field in the login form.
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
//checking whether datareader contains any rows or not. If the condition
//is true then the code below will be executed otherwise code in else
//block will be executed.
while (rdr.Read())
{
//Reading all records fetched, one by one and matching with the user name
//and password entered by user, in order to overcome small and upper caps
//complexities in user name and password.
if (rdr[0].ToString().ToUpper() ==txtUserName.Text.Trim().ToUpper() && txtPassword.Text==rdr[1].ToString())
{
log= true;
this.Close();
}
else
{
//If username or password provider by the user are incorrect then
//following message will be displayed.
MessageBox.Show("User Name or Password incorrect!!!");
txtUserName.Text= "";
txtPassword.Text= "";
txtUserName.Focus();
log= false;
}
}
}
else
{
MessageBox.Show("User Name or Password incorrect!!!");
txtUserName.Text = "";
txtPassword.Text = "";
txtUserName.Focus();
log = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
fnlogin();
}
private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
//Checking whether enter key is pressed in text boxes or not.
if (e.KeyChar == (char)13)
fnlogin();
}
//Setting property of this form in order to use it in another form
//so as to get the information whether the login was successful or not.
public Boolean pLog
{
get
{
return log;
}
set
{
log = value;
}
}
Screen Shot

Message displayed if
username and password provider are incorrect.
Leave Comment
3 Comments