-1

I want to delete a record of the database.I want first to check if this record exist and if exist to proceed but if it isn't exist to diplay a message with a message box.I don't know how to set this check.Any ideas? Here is my code:

if (textBoxCode.Text != String.Empty && textBoxLastName.Text != String.Empty && textBoxFirstName.Text != String.Empty)

{
  con.Open();

  SqlCommand cmd = con.CreateCommand();
  cmd.CommandType = CommandType.Text;
  cmd.CommandText = "delete from Student where Code='" + textBoxCode.Text + "' and Last_Name='" + textBoxLastName.Text + "' and First_Name='" + textBoxFirstName.Text + "'";
  cmd.ExecuteNonQuery();

  con.Close();
  DisplayData();

  MessageBox.Show("Student deleted successfully", "Delete Done", MessageBoxButtons.OK);

  textBoxCode.Text = String.Empty;
  textBoxFirstName.Text = String.Empty;
  textBoxLastName.Text = String.Empty;

}
  • 11
    First, read about SQL Injection and how to use parameterized queries., Second, ExecuteNonQuery returns the number of rows effected by the sql statement, so if it returns 0, it means no row was found and therefor no row was deleted, so you don't need to check if it exists before. – Zohar Peled Feb 04 '18 at 15:20
  • 1
    Do a Select Query. The cmdExecuteQuery() method returns the number of rows found. So zero indicates the vaue is not in the database. – jdweng Feb 04 '18 at 16:53

1 Answers1

2

You can use the return value of ExecuteNonQueryfunction.

if (textBoxCode.Text != String.Empty && textBoxLastName.Text != String.Empty && textBoxFirstName.Text != String.Empty)
{

    con.Open();

    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "delete from Student where Code=@Code and Last_Name=@Last_Name and First_Name=@First_Name";
    cmd.Parameters.AddWithValue("@Code", textBoxCode.Text);
    cmd.Parameters.AddWithValue("@Last_Name", textBoxLastName.Text);
    cmd.Parameters.AddWithValue("@First_Name", textBoxFirstName.Text);

    int rc = cmd.ExecuteNonQuery();

    if (rc > 0)
    {
        MessageBox.Show("Student deleted successfully", "Delete Done", MessageBoxButtons.OK);
    }
    else
    {
        MessageBox.Show("There is no record found for delete!", "Delete Done", MessageBoxButtons.OK);
    }
    con.Close();
    DisplayData();

    textBoxCode.Text = String.Empty;
    textBoxFirstName.Text = String.Empty;
    textBoxLastName.Text = String.Empty;

}
Serkan Arslan
  • 13,158
  • 4
  • 29
  • 44