繁体   English   中英

无法从表单中删除记录

[英]Cant delete a record from the form

我有两种形式。 一种是输入库存,另一种是在网格视图中查看库存。 所以现在当我需要删除一条记录时,我曾经从网格视图中选择记录,然后双击该单元格,那么“库存条目”将与所有现有记录一起打开。 然后,当我单击“删除按钮”时,它表示已成功删除,但在网格视图或数据库中未进行任何更改。数据仍然存在。 请帮我谢谢。

链接到我的sql: https : //drive.google.com/open? id = 1D5EpLZZ- 2yVlOphaSBxOSC2vVLGabZ7W

我的ID设置为自动递增,并且索引类型设置为我的股票为“唯一”

private void bunifuFlatButton3_Click(object sender, EventArgs e)
{
 try
    {
        conn.Close();
        conn.Open();
        String DeleteQuery = "Delete from Stock_Jewelry where ID ='" + txt_ID + "';";
        SqlDataAdapter execute = new SqlDataAdapter(DeleteQuery, conn);
        execute.SelectCommand.ExecuteNonQuery();
        MessageBox.Show("You've deleted successfully!", "Successful Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        conn.Close();
        this.Close();
    }

    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    conn.Close();
}

请尝试执行此操作,因为Id类型为int且txt_ID必须转换为int;

String DeleteQuery = "Delete from Stock_Jewelry where ID =" + txt_ID;

正如人们提到的那样,您的代码注入不安全,因此最好使用SqlParameter解决问题:

通过SqlDataAdapter尝试一下:

   try
   {
        SqlConnection connection = new SqlConnection(conn);
        SqlDataAdapter adapter = new SqlDataAdapter();
        connection.Open();
        adapter.DeleteCommand = connection.CreateCommand();
        adapter.DeleteCommand.CommandText = "Delete from Stock_Jewelry where ID =@id";
        adapter.DeleteCommand.Parameters.AddWithValue("@id", txt_ID.Trim());
        adapter.DeleteCommand.ExecuteNonQuery();
        MessageBox.Show("Row(s) deleted !! ");
    }
    catch (Exception ex)
    {
            MessageBox.Show(ex.ToString());
    }

或最简单的方式:

SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("Delete from Stock_Jewelry where ID =@id", con);
con.Open();
cmd.Parameters.AddWithValue("@id", txt_ID.Trim());
cmd.ExecuteNonQuery();

注意:

当Query在DB中运行时没有问题,这意味着您的代码没有问题,否则让我们知道另一端是什么异常,则txt_ID存在问题,例如其中有空格,或者DB中不存在输入的ID 。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM