从数据网格视图中删除数据

时间:2017-12-16 11:29:26

标签: c#

我通过我的系统从MS Access数据库中删除数据。

幸运的是它正在运行但是,当我点击删除按钮,而不是一次删除一个数据时,所有数据都被删除了一次。

这里的错误是什么?

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);
    }
}

3 个答案:

答案 0 :(得分:2)

您没有使用where子句传递任何条件,请在查询中传递索引,如下所示

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

答案 1 :(得分:0)

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);
    }
}

获取Row索引并将其传递给查询以删除该特定行

答案 2 :(得分:0)

在您的按钮点击事件中,您还没有指定要在您正在使用的SQL查询中删除哪条记录。因此查询将删除表中的所有数据。如果您有一个主键或一列可以唯一标识表中的记录,您可以专门说删除表中的特定记录。在您的情况下,您应该在查询中指定原始索引。尝试使用以下。:

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);
    }
}