【发布时间】: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
}
}
}
【问题讨论】:
标签: c# datagridview sql-server-ce