none
C# if statement to check if user excist in database

    Question

  • Hello 

    im trying to learn C# and cant seem to figure out what code to write to check if username ( and email ) already excist in datbase.. 

    so this is me 5 hours later ... writing for help in here :

    i know i need an somekind of if statement so if username already excist then true / false

    just donno how to actualy do the code.

    private void button1_Click(object sender, EventArgs e)
            {
             if (txtusername.Text == "" & txtEmail.Text != "" & txtpassword.Text != "" & txtcpass.Text != "")
            {
                cn.Open();
                cmd.CommandText = "insert into Login (username,email,password,cpass) values ('" + this.txtusername.Text + "','" + this.txtEmail.Text + "','" + this.txtpassword.Text + "','" + this.txtcpass.Text + "')";
                cmd.ExecuteNonQuery();
                cmd.Clone();
                MessageBox.Show("Record inserted!");
                cn.Close();
                txtusername.Text = "";
                txtEmail.Text = "";
                txtpassword.Text = "";
                txtcpass.Text = "";
                loadlist();
                }
                }        

    Sunday, March 26, 2017 9:41 AM

All replies

  • In my opinion this feature is more reliable to implement on database level: defining username and email as a compound Primary Key of the Login table. It depends on the type of database (MSSQL, Access, etc.) and can be done during the design of the table.

    Then you will receive an exception that can be intercepted with try-catch statement.

    By the way, you do not have to call Clone. And it is safer to use parameterised queries and using statements.

    Sunday, March 26, 2017 10:00 AM