Cool Heng

Cool Heng

  • NA
  • 17
  • 10.2k

Validate the data weather its exist in the database before add a data in the database

Oct 9 2012 11:08 AM
protected void btnSubmit_Click(object sender, EventArgs e)
{
   
SqlConnection conNwind;
   
SqlCommand cmdSelect, cmdInsert;
   
SqlDataReader dtrUser;

   
string connStr = ConfigurationManager.ConnectionStrings["ConnectionNWind"].ConnectionString;
    conNwind
= new SqlConnection(connStr);

    conNwind
.Open();

   
string select = "Select * from UserRegistration where UserName=@UN AND Email=@Email";
    cmdSelect
= new SqlCommand(select, conNwind);

    cmdSelect
.Parameters.AddWithValue("@UN", txtUN.Text);
    cmdSelect
.Parameters.AddWithValue("@Email", txtEmail.Text);
    dtrUser
= cmdSelect.ExecuteReader();


   
if (dtrUser.Read())
   
{
       
if (Username != "")
       
{
           
Label1.Text = "UserName already exists";
       
}


       
else if (Email != "")
       
{
           
Label1.Text = "Email already exist!";


       
}

       
else
       
{
            dtrUser
.Close();
           
string strInsert = "Insert into UserRegistration(FirstName,LastName,UserName,Password,Gender,Address,Email) values(@FN,@LN,@UN,@Pass,@Gender,@Add,@Email)";

            cmdInsert
= new SqlCommand(strInsert, conNwind);

            cmdInsert
.Parameters.AddWithValue("@FN", txtFN.Text);
            cmdInsert
.Parameters.AddWithValue("@LN", txtLN.Text);
            cmdInsert
.Parameters.AddWithValue("@UN", txtUN.Text);
            cmdInsert
.Parameters.AddWithValue("@Pass", txtPass.Text);
            cmdInsert
.Parameters.AddWithValue("@Gender", rdlGender.SelectedItem.ToString());
            cmdInsert
.Parameters.AddWithValue("@Add", txtAdd.Text);
            cmdInsert
.Parameters.AddWithValue("@Email", txtEmail.Text);

           
int intAdd = cmdInsert.ExecuteNonQuery();

           
if (intAdd != 0)
               
Label1.Text = "User Registration successful,you can now <a href='UserLogin.aspx'>Login</a>";

           
else
               
Label1.Text = "Record not added into database!";
       
}
   
}

   
else
        conNwind
.Close();

}
I want to check the record weather its exits in the database(which is the username and the email address) before user insert, but i have a problem which highlighted in yellow color which shown above.

Answers (15)