【发布时间】:2021-03-27 19:25:02
【问题描述】:
在我的 WinForms 应用程序中,我需要同时从数据网格视图和数据库中删除选定的行并保存数据库。
我有这个下面的代码,现在它只从 datagridview 中删除,而不是从数据库中删除,请指导我哪里错了。
private void button1_Click(object sender, EventArgs e)
{
try
{
String msg = "Confirm Delete?";
String caption = "Delete Record";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
MessageBoxIcon ico = MessageBoxIcon.Question;
DialogResult result;
result = MessageBox.Show(this, msg, caption, buttons, ico);
if (result == DialogResult.Yes)
{
foreach (DataGridViewRow item in this.iP_SpoolsDataGridView.SelectedRows)
{
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = con.CreateCommand();
int id = Convert.ToInt32(iP_SpoolsDataGridView.SelectedRows[0].Cells[0].Value);
cmd.CommandText = "Delete from Lot_Numbers where ID='" + id + "'";
iP_SpoolsDataGridView.Rows.RemoveAt(this.iP_SpoolsDataGridView.SelectedRows[0].Index);
con.Open();
cmd.ExecuteNonQuery();
}
}
}
else
{
return;
}
}
catch (Exception ex)
{
MessageBox.Show("Deleting Failed:" + ex.Message.ToString(), "Delete",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
【问题讨论】:
-
它抛出异常?如果是,什么样的例外?
标签: c# sql-server visual-studio winforms