C# 从datagridview值中删除数据库中的行
我有一个未绑定的DataGridView,它显示在上一个表单上选择的DataTable数据。如果我希望从DataGridView中删除DataRow,我希望它更新数据库。我有一些代码,但它不能正常工作,它只是删除第一行,而不是删除选定的行(我想删除它,因为它的值)。是否有方法获取单元格值并通过查询将其从数据库中删除?我正在使用SQLCE3.5C# 从datagridview值中删除数据库中的行,c#,datagridview,sql-server-ce,C#,Datagridview,Sql Server Ce,我有一个未绑定的DataGridView,它显示在上一个表单上选择的DataTable数据。如果我希望从DataGridView中删除DataRow,我希望它更新数据库。我有一些代码,但它不能正常工作,它只是删除第一行,而不是删除选定的行(我想删除它,因为它的值)。是否有方法获取单元格值并通过查询将其从数据库中删除?我正在使用SQLCE3.5 private void removeBTN_Click(object sender, EventArgs e) {
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
}
}
}
private void removeBTN_单击(对象发送方,事件参数e)
{
string tableName=Data[“quote Name”]。ToString().Trim();//获取表名
if(MessageBox.Show(“是否确实要删除此项目?”,“确认删除”,MessageBoxButtons.YesNo)=DialogResult.Yes)
{for(int i=0;i
@user3521452更新了答案,必须用单引号对参数进行排序“谢谢,伙计,我看看进展如何。当我单击button@user3521452更新答案,忘记单引号,添加if以避免空引用异常并关闭connection@user3521452您可以将datagridview的SelectionMode属性设置为FullRowSelect
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
}
}
}