从datagridview值中删除数据库中的行
Posted
技术标签:
【中文标题】从datagridview值中删除数据库中的行【英文标题】:Deleting row from database from datagridview value 【发布时间】:2014-06-29 23:55:47 【问题描述】:我有一个未绑定的 DataGridView,它显示在前一个表单上选择的 DataTable 数据。如果我想从 DataGridView 中删除一个 DataRow,我希望它更新 DataBase。我有一些代码,但它不能正常工作,它只是删除第一行,而不是删除选定的行(因为它的值我想删除它)。有没有办法获取单元格值并通过查询将其从 DateBase 中删除?我正在使用 SqlCe 3.5
private void removeBTN_Click(object sender, EventArgs e)
string tableName = Data["Quotation Name"].ToString().Trim(); //gets the table name
if (MessageBox.Show("Are you sure you want to remove this item? ", "Confirm Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
for (int i = 0; i < dataGridView1.Rows.Count - 0; i++)
string constring = @"Data Source=|DataDirectory|\LWADataBase.sdf";
string Query = "delete from [" + tableName + "] where [Item Name] = @item ";
SqlCeConnection conDataBase = new SqlCeConnection(constring);
SqlCeCommand cmd = new SqlCeCommand(Query, conDataBase);
cmd.Parameters.Add("@item", dataGridView1.Rows[i].Cells[0].Value.ToString());
try
conDataBase.Open();
cmd.ExecuteNonQuery();
//displays a system error message if a problem is found
catch (Exception ex)
MessageBox.Show(ex.Message);
getTable(); //loads the table into the DGV
【问题讨论】:
【参考方案1】:private void removeBTN_Click(object sender, EventArgs e)
string tableName = Data["Quotation Name"].ToString().Trim(); //gets the table name
if (MessageBox.Show("Are you sure you want to remove this item? ", "Confirm Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
foreach (DataGridViewRow r in quotation_NameDataGridView.SelectedRows)
string constring = @"Data Source=|DataDirectory|\LWADataBase.sdf";
string Query = "delete from [" + tableName + "] where [Item Name] like @item";
SqlCeConnection conDataBase = new SqlCeConnection(constring);
SqlCeCommand cmd = new SqlCeCommand(Query, conDataBase);
if (r.Cells[0] != null)
cmd.Parameters.Add("@item", r.Cells[0].Value.ToString());
try
conDataBase.Open();
int res = cmd.ExecuteNonQuery();
conDataBase.Close();
//displays a system error message if a problem is found
catch (Exception ex)
MessageBox.Show(ex.Message);
getTable(); //loads the table into the DGV
【讨论】:
@user3521452 更新了答案,参数必须用单引号括起来' 谢谢哥们,我看看怎么样。 单击按钮时仍然没有任何反应 @user3521452 更新答案,忘记单引号,加个if避免空引用异常并关闭连接 @user3521452 您可以将datagridview的SelectionMode属性设置为FullRowSelect以上是关于从datagridview值中删除数据库中的行的主要内容,如果未能解决你的问题,请参考以下文章