I have an unbound DataGridView which displays DataTable data selected on the previous form. If I wish to remove a DataRow from the DataGridView, I'd like it to update the DataBase. I have some code, but it doesn't work properly, it just deletes the first row, instead of deleting the selected row (which I want to delete because of its value). Is there a way to obtain the cell value and pass through a query to delete it from the DateBase? I'm using 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
}
}
}
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
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.