RossH RossH - 5 months ago 8
MySQL Question

Delete Button SQL Database Windows Form Application

How can I modify my delete button code to delete a selected row from my SQL database? Currently when I select one row and click the delete button all the rows are deleted.

private void delete_button1_Click_1(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0)
{
int selectedIndex = dataGridView1.SelectedRows[0].Index;
string sqlquery;
string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
MySqlConnection con = new MySqlConnection(ConString);
con.Open();
int rowID = int.Parse(dataGridView1[0, selectedIndex].Value.ToString());
sqlquery = "DELETE FROM hotel_booking WHERE BookingID = BookingID";

try
{
MySqlCommand command = new MySqlCommand(sqlquery, con);
command.ExecuteNonQuery();
string CmdString = "SELECT * FROM hotel_booking";
MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, con);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

Answer

Do not try to run this query, it will delete all of your rows

DELETE FROM hotel_booking WHERE BookingID = BookingID

BookingID = BookingID means it is always true

I think you are trying to use

int rowID = int.Parse(dataGridView1[0, selectedIndex].Value.ToString());
sqlquery = "DELETE FROM hotel_booking WHERE BookingID = "+ rowID;
Comments