Search code examples
c#sql-server-ce

Login Page C# .SDF


I am trying to create an application that allows a user to log in using .sdf, there is not much on the internet about this!

Could really do with some pointers.

This is what I currently have but I believe it is a pile of mess as no matter what I type in each text box it will redirect me to Form2 (which is kinda expected). I know I need an if statement somewhere but not sure how to implement:

  private void Login_Click(object sender, EventArgs e)
  {
     using (SqlCeConnection yourConnection = new SqlCeConnection("Data Source=C:\\Users\\Username\\Documents\\Databases\\New Folder\\Login.sdf"))
     {
          string query = "SELECT * FROM tbl_employees where Username like '" + textBox1.Text + "' AND Password like '" + textBox2.Text +"'";
          SqlCeDataAdapter dA = new SqlCeDataAdapter(query, yourConnection);
          SqlCeCommandBuilder cBuilder = new SqlCeCommandBuilder(dA);

          this.Hide();
          Form2 secondForm = new Form2();
          secondForm.ShowDialog();
     }
 }      

Solution

  • First, SQL Server CE database i.e .sdf file is just another storage file. It is very very light and portable version of SQL Server.

    But, at most, your code and logicwould be similar to the one for SQL Server. Just different classes. i.e SqlCeConnection, SqlCeCommand and so on.

    Now you need to verify that your connectionString is correct.

    string connectionString ="data source=physical path to .sdf file; 
                             password=pwdThtUSet; persist security info=True";
    
    using (SqlCeConnection yourConnection = new SqlCeConnection(connectionString))
    {
           ....your logic
    }
    

    Now, in your query to search for the username and password combination matching row, don't do it with like because you need exact match.

    so do it like:

         string query = "SELECT * FROM tbl_employees where Username ='" + textBox1.Text + "' AND Password ='" + textBox2.Text +"'";
          SqlCeDataAdapter dA = new SqlCeDataAdapter(query, yourConnection);
          DataTable dt = new DataTable();
          dA.Fill(dt);
    
          if(dt.Rows.Count>0)
          {
              this.Hide();
              Form2 secondForm = new Form2();
              secondForm.ShowDialog();
          }