user9056318
user9056318

Reputation: 19

Delete Data from Data Grid View

I'm deleting data from the MS Access database through my system.

Fortunately it's running but, as I click delete button, instead of deleting one data at a time, all of the data was deleted in one click.

What could be the error here?

private void bttnDelete_Click(object sender, EventArgs e)
{
    try
    {
        connection.Open();
        OleDbCommand command = new OleDbCommand();
        command.Connection = connection;
        string query = "delete from tblBookMaint where BookNumber";
        command.CommandText = query;

        command.ExecuteNonQuery();
        MessageBox.Show("Data Deleted!");
        connection.Close();
        load();
        clearTxts();
        Panel.Enabled = false;
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error " + ex);
    }
}

Upvotes: 1

Views: 69

Answers (2)

Sajeetharan
Sajeetharan

Reputation: 222532

You are not passing any condition with your where clause, pass the index in your query as below

 string query = "delete from tblBookMaint where BookNumber= "+index+" ";

Upvotes: 1

Sridhar Rajan
Sridhar Rajan

Reputation: 105

private void bttnDelete_Click(object sender, EventArgs e)
{
    try
    {
        connection.Open();
        OleDbCommand command = new OleDbCommand();
        command.Connection = connection;
        int index = Convert.ToInt32(e.RowIndex);
        string query = "delete from tblBookMaint where BookNumber= "+index+" ";
        command.CommandText = query;

        command.ExecuteNonQuery();
        MessageBox.Show("Data Deleted!");
        connection.Close();
        load();
        clearTxts();
        Panel.Enabled = false;
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error " + ex);
    }
}

Get the Row index and pass it to the query to delete that particular row

Upvotes: 0

Related Questions