我有一个未绑定的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
}
}
}
答案 0 :(得分:0)
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
}
}
}