从数据网格视图和数据库中删除选定的行
Posted
技术标签:
【中文标题】从数据网格视图和数据库中删除选定的行【英文标题】:Delete selected rows from data grid view and database 【发布时间】: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);
【问题讨论】:
它抛出异常?如果是,什么样的例外? 【参考方案1】:试试这个:
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;
【讨论】:
为了获得高质量的答案,除了提供代码之外,请说明您所做的更改。以上是关于从数据网格视图和数据库中删除选定的行的主要内容,如果未能解决你的问题,请参考以下文章
第十三部分网格视图:删除新添加的行(尚未存入数据库),原来数据行不删除