C# 从数据网格视图和数据库中删除选定行
在我的WinForms应用程序中,我需要同时从数据网格视图和数据库中删除选定行并保存数据库 我有下面的代码,现在它只是从datagridview中删除,而不是从数据库中删除,请指导我哪里错了C# 从数据网格视图和数据库中删除选定行,c#,sql-server,visual-studio,winforms,C#,Sql Server,Visual Studio,Winforms,在我的WinForms应用程序中,我需要同时从数据网格视图和数据库中删除选定行并保存数据库 我有下面的代码,现在它只是从datagridview中删除,而不是从数据库中删除,请指导我哪里错了 private void button1_Click(object sender, EventArgs e) { try { String msg = "Confirm Delete?"; String caption = "De
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);
}
试试这个:
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)
{
int id = 0;
foreach (DataGridViewRow item in this.iP_SpoolsDataGridView.SelectedRows)
{
id = Convert.ToInt32(item.Cells[0].Value.ToString());
if (Database_Remove_LotNumberById(id))
{
iP_SpoolsDataGridView.Rows.RemoveAt(item.Index);
}
}
}
else
{
return;
}
}
catch (Exception ex)
{
MessageBox.Show("Deleting Failed:" + ex.Message.ToString(), "Delete",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
//The code become clean if you separate the Database Operations
private bool Database_Remove_LotNumberById(int IdLotNumber)
{
bool IsRemovedFromDatabase = false;
try
{
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "Delete from Lot_Numbers where ID= @ID";
cmd.Parameters.AddWithValue("@ID", IdLotNumber);
con.Open();
cmd.ExecuteNonQuery();
IsRemovedFromDatabase = true;
}
}
catch (SqlException ex)
{
// Handle the SQL Exception as you wish
MessageBox.Show("Deleting Failed:" + ex.Message.ToString(), "Delete", MessageBoxButtons.OK, MessageBoxIcon.Error);
//or throw
}
return IsRemovedFromDatabase;
}
它抛出一个异常?。如果是,什么样的例外?为了获得高质量的答案,除了提供代码外,请解释您更改了什么。