Advertisement
Guest User

Login SQL database code

a guest
Apr 22nd, 2017
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.13 KB | None | 0 0
  1. public partial class frmLogin : Form
  2.     {
  3.         public frmLogin()
  4.         {
  5.             InitializeComponent();
  6.         }
  7.         //Connection string
  8.         string cs = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Pontus\Documents\Visual Studio 2017\Projects\Test\Login\Login\login.mdf;Integrated Security=True;Connect Timeout=30";
  9.        
  10.         private void btn_Submit_Click(object sender, EventArgs e)
  11.         {
  12.             if (txt_Username.Text=="" || txt_Password.Text=="")
  13.             {
  14.                 MessageBox.Show("Please provide Username and Password.");
  15.                 return;
  16.             }
  17.             try
  18.             {
  19.                 //Create SQLConnection
  20.                 SqlConnection con = new SqlConnection(cs);
  21.                 SqlCommand cmd = new SqlCommand("SELECT * FROM tbl_Login WHERE Username=@Username AND Password=@password", con);
  22.                 cmd.Parameters.AddWithValue("@Username", txt_Username.Text);
  23.                 cmd.Parameters.AddWithValue("@Password", txt_Password.Text);
  24.                 con.Open();
  25.                 SqlDataAdapter adapt = new SqlDataAdapter(cmd);
  26.                 DataSet ds = new DataSet();
  27.                 adapt.Fill(ds);
  28.                 con.Close();
  29.                 int count = ds.Tables[0].Rows.Count;
  30.                 //If count is equal to 1, then show frmmain Form
  31.                 if (count == 1)
  32.                 {
  33.                     MessageBox.Show("Login Successful!");
  34.                     this.Hide();
  35.                     frmAdmin fa = new frmAdmin();
  36.                     fa.Show();
  37.                 }
  38.                 else
  39.                 {
  40.                     MessageBox.Show("Login Failed!");
  41.                 }
  42.             }
  43.             catch (Exception ex)
  44.             {
  45.                 MessageBox.Show(ex.Message);
  46.             }
  47.                 }
  48.  
  49.         private void frmLogin_Load(object sender, EventArgs e)
  50.         {
  51.  
  52.         }
  53.  
  54.         private void checkBox_Show_Password_CheckedChanged(object sender, EventArgs e)
  55.         {
  56.             txt_Password.PasswordChar = checkBox_Show_Password.Checked ? '\0' : '*';
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement