1
Answer

What it wrong with this function ?

Jahangir Khan

Jahangir Khan

8y
371
1
  1. private void btnAdd_Click(object sender, EventArgs e)  
  2.      {  
  3.          {  
  4.              con.Open();  
  5.              //string Sql = "INSERT INTO Members ( MemberId, Name, Address, Mobile, Email ) VALUES " + " (@Id, @name, @address, @mobile, @email)";  
  6.   
  7.              string Sql = "INSERT INTO Members ( MemberId, Name, Address, Mobile, Email ) VALUES " + " (@Id, @name, @address, @mobile, @email); SELECT MemberId FROM Members WHERE NOT EXISTS (SELECT * FROM Members WHERE MemberId = @Id AND Name = @name AND Address = @address AND Mobile = @mobile AND Email = @email)";  
  8.   
  9.              using (SqlCommand cmd = new SqlCommand(Sql, con))  
  10.              {  
  11.                  cmd.CommandText = Sql;  
  12.                  cmd.Parameters.AddWithValue("@Id", tbID.Text);  
  13.                  cmd.Parameters.AddWithValue("@name", tbName.Text);  
  14.                  cmd.Parameters.AddWithValue("@address", tbAddress.Text);  
  15.                  cmd.Parameters.AddWithValue("@mobile", tbMobile.Text);  
  16.                  cmd.Parameters.AddWithValue("@email", tbEmail.Text);  
  17.                  cmd.ExecuteNonQuery();  
  18.   
  19.                  //Sql = "INSERT INTO Payments ( MemberId, [Year], [Amount] ) VALUES " + "(@id, @year, @amount)";  
  20.                  Sql = "INSERT INTO Payments ( MemberId, [Year], [Amount] ) VALUES " + "(@id, @year, @amount) SELECT MemberId FROM Payments WHERE NOT EXISTS (SELECT * FROM Payments WHERE [Year] = @year AND [Amount] = @amount)";  
  21.                  cmd.Parameters.Clear();  
  22.                  cmd.CommandText = Sql;  
  23.                  cmd.Parameters.AddWithValue("@Id", tbID.Text);  
  24.                  cmd.Parameters.AddWithValue("@year", tbYear.Text);  
  25.                  cmd.Parameters.AddWithValue("@amount", tbAmount.Text);  
  26.                  cmd.ExecuteNonQuery();  
  27.   
  28.                  MessageBox.Show("Data Added");  
  29.                  tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbMobile.Clear(); tbEmail.Clear(); tbYear.Clear(); tbAmount.Clear();  
  30.                  con.Close();  
  31.              }  
  32.          }  
  33.      }  
I have 2 tables "Members" & "Payments" When I enter one new record it records its and then if I enter the same over and over again it duplicates it many times which it "SHOULD NOT" I should get warning that it already exists. some how I am stuck with this can anyone assist !  
Answers (1)