C# 如何删除DataGridView中的多行或所有行?
我想使用C# 如何删除DataGridView中的多行或所有行?,c#,winforms,datagridview,C#,Winforms,Datagridview,我想使用DataGridView删除数据库中的多行或所有行。 例如如果在DataGridView中有10行,则应选择并删除所有10行。下面是我使用DataGridView删除数据库中单行的代码 private void btnDeleteProduct_Click(object sender, EventArgs e) { ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrin
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");
}
}
有人能帮我修改代码吗?首先,您不应该使用
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();
我想最好在循环外部打开和关闭连接,否则就打开和关闭它unnecessarily@MongZhu,这是个好建议。但是,一行一行地删除所有行的想法也很糟糕……我同意,但我忘了如何构建列表并在中使用关键字
:D否则我会写一个答案:)@MongZhu是的,我想到了,但我现在懒得写了……)@哈姆斯读到关于。。。而且是强制性的