1. First make separate Class for Login. before that first add ConfigurationManager to your References.
2. Add connectionStrings to App.config File
<connectionStrings>
<add name="connstrng" connectionString="Data Source=.;Initial Catalog=mmis;Integrated Security=True;"/>
</connectionStrings>
3. Example : ClassFolder > MainClass.cs
4. Create getter setter method to MainClass.cs
//login getter setter
public int login_id { get; set; }
public string login_username { get; set; }
public string login_password { get; set; }
public string login_role { get; set; }
//connection string
static string myconnstrng=ConfigurationManager.ConnectionStrings["connstrng"].ConnectionString;
//function for login section
public bool Login(MainClass c){
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstrng);
DataTable dt = new DataTable();
try{
string sql = "SELECT * FROM tbllogin WHERE login_username=@login_username AND login_password=@login_password AND login_role=@login_role";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@login_username", c.login_username);
cmd.Parameters.AddWithValue("@login_password", c.login_password);
cmd.Parameters.AddWithValue("login_role", c.login_role);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
conn.Open();
adapter.Fill(dt);
int count = dt.Rows.Count;
if (count == 1){
isSuccess = true;
}
else{
isSuccess = false;
}
}
catch (Exception ex){
}
finally{
conn.Close();
}
return isSuccess;
}
After that create a Login form.
Add using MMIS.ClassFolder; to predefined section
MainClass c = new MainClass();
private void btnLogin_Click(object sender, EventArgs e)
{
c.login_username = txtUsername.Text;
c.login_password = txtPassword.Text;
if (checkBoxLoginUser.Checked == true) {
c.login_role = checkBoxLoginUser.Text;
}
else if (checkBoxLoginAdmin.Checked == true) {
c.login_role = checkBoxLoginAdmin.Text;
}
else {
c.login_role = checkBoxLoginController.Text;
}
Boolean success = c.Login(c);
if (success == true)
{
MessageBox.Show("Login Success.");
}
else
{
MessageBox.Show("Invalid Credentials. Please provide correct information.");
}
}
IDE Used To Test This Code : Visual Studio.
Try this code in your computer for better understanding. Enjoy the code. If you have any Question you can contact us or mail us.We will reply you as soon as possible.
Post a Comment