I have a slight issue in my C# code in Asp.net when deleting a row from sql server. I am using ExecuteNonQuery to determine which message I render to the page. If ExecuteNonQuery returns a 1 then I display success message. Where I am becoming stuck is I have the same logic for adding a record and updating a record and my code works fine. See below for the code.
private void Delete_row(string ImageId)
{
string sSQL = "delete FROM dbo.Image_library_UK_temp where Image_id=" + ImageId;
using (SqlConnection dbConnection = new SqlConnection(app_settings.sql_conn_string_db))
{
try
{
//delete the row from db
dbConnection.Open();
SqlCommand command = new SqlCommand(sSQL, dbConnection);
command.CommandType = CommandType.Text;
command.CommandTimeout = 1024;
command.ExecuteNonQuery();
int rowsAffected = command.ExecuteNonQuery();
if (rowsAffected == 1)
{
messagepanel1.ShowSuccessMessage("The image " + txtImgTitle.Text + "has been deleted from the system.");
DisableValidation();
}
}
catch (Exception ex)
{
messagepanel1.ShowErrorMessage("Error: Deletion unsuccessful");
}
Session.RemoveAll();
generateTable(false);
}
}
Rows affected currently returns 0. This is a simple SQL statement so my sql is hard-coded in C# and I am not using a stored procedure.
Any ideas how I can make this work?
You’re executing the command twice.
The first line will delete the row and return 1, but you’re ignoring the return value.
The second line will execute the
DELETEstatement again, but it won’t delete anything, because there is no more rows satisfying the given condition; thus,rowsAffectedwill be zero.Also, your code is vulnerable to sql injections, as was already mentioned in comments. Consider using prepared statements instead.