gpt4 book ai didi

c# - 如何创建 "Delete button for deleting grid columns from SQL Server database in C#"?

转载 作者:行者123 更新时间:2023-11-30 17:27:03 24 4
gpt4 key购买 nike

我需要一部分代码,我可以通过单击 delete 按钮从数据库中删除网格列或行,这应该使用 C# 完成。

我尝试通过 MVVM 架构删除它,但我相信我写错了。还有其他方法吗?

public void DeleteAuction()
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnString"].ToString();
conn.Open();

SqlCommand command = new SqlCommand("UPDATE AuctionTbl2 SET deleted = 1 WHERE id = @Id", conn);

SqlParameter myParam = new SqlParameter("@Id", SqlDbType.Int, 11);
myParam.Value = this.Id;

command.Parameters.Add(myParam);

int rows = command.ExecuteNonQuery();
}
}

现在我创建了构造函数、属性和字段,一切正常。我尝试将数据从 SQL Server 连接到 C#,这也工作正常,但是当我按下 delete 按钮时它不起作用。没有错误,什么都没有。请帮忙,我现在非常绝望。

[ This is when delete is clicked, it should go in DB from 0 --> 1 for deleted[1]

Like this

最佳答案

更新:您应该试试这段代码,我已经亲自测试过它,运行起来非常棒。如果它能满足您的需求,请告诉我。

public void DeleteAuction()
{
try
{
bool isSuccess = false;
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnString"].ToString();
conn.Open();
SqlCommand command = new SqlCommand("UPDATE AuctionTbl2 SET deleted = 1 WHERE id = @Id", conn);
command.Parameters.AddWithValue("@Id",Id);
int rows = command.ExecuteNonQuery();
if(rows>0)
{
MessageBox.Show("Deletion Successfull");
dt = selectAuction();
auctionDataGridView.DataSource = dt;
}
else
MessageBox.Show("Deletion Unsuccessfull");
}
}
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}

//method to update the dataGridView after deletion
public DataTable selectAuction()
{
try
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnString"].ToString();
conn.Open();
String sql = "select * from AuctionTbl2";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter adaptor = new SqlDataAdapter(cmd);
adaptor.Fill(table);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
con.Close();
}
return table;
}

注意:我试过像你一样使用变量,但如果有一个鬼鬼祟祟不同的变量名,请原谅我。

关于c# - 如何创建 "Delete button for deleting grid columns from SQL Server database in C#"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55550460/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com