我想使用DataGridView
删除数据库中的多行或所有行。
例如。如果DataGridView
中有10行,则应选择并删除所有10行。以下是使用DataGridView
删除数据库中单行的代码。
private void btnDeleteProduct_Click(object sender, EventArgs e)
{
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["MyDBConnectionString"];
string connectionString = conSettings.ConnectionString;
if (ProductServicesDataGrid.CurrentRow.Selected)
{
string selectedCode = ProductServicesDataGrid.CurrentRow.Cells[0].Value.ToString();
conn = new SqlConnection(connectionString);
try
{
conn.Open();
cmd = new SqlCommand("DELETE FROM ProductServices where ProductCode='" + selectedCode + "' ", conn);
sdr = cmd.ExecuteReader();
loadProductServicesTable();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
else
{
MessageBox.Show("Row is not Selected");
}
}
有人可以帮助我并修改我的代码吗?
答案 0 :(得分:1)
首先,您不应该使用CurrentRow
属性,因为它只返回一行。代替。使用SelectedRows
集合并迭代它。
其次,从不在命令文本中连接参数。相反,请使用参数化查询。
//connection.Open is moved out of the loop, to avoid unnecessary open/close
conn = new SqlConnection(connectionString);
conn.Open();
try
{
foreach (var row in ProductServicesDataGrid.SelectedRows)
{
string selectedCode = row.Cells[0].Value.ToString();
try
{
cmd = new SqlCommand("DELETE FROM ProductServices where ProductCode=@productCode", conn);
cmd.Parameters.Add(.Parameters.Add("productCode", SqlDbType.VarChar).Value = selectedCode;
sdr = cmd.ExecuteReader();
//this probably shouldn't be here, but outside the foreach loop.
//that way table will be loaded after deletion of those n rows.
//loadProductServicesTable();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
//refresh products after deletion
loadProductServicesTable();