如何使用复选框删除DataGridView中的多行

本文关键字:DataGridView 何使用 复选框 删除 | 更新日期: 2023-09-27 18:11:40

如何使用CheckBox删除DataGridView中的多行?

我找不到我犯错误的地方,但是代码抛出一个错误,解释没有定义参数。

DataGridViewRow row = new DataGridViewRow();
SqlCommand delcommand = new SqlCommand();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    row = dataGridView1.Rows[i];
    if (Convert.ToBoolean(row.Cells[10].Value) == true)
    {
        int id = Convert.ToInt16(dataGridView1.SelectedRows[dataGridView1.SelectedCells[0].RowIndex].Cells[0].Value);
        delcommand.Connection = connection;
        delcommand.CommandText = "DELETE FROM TFirmaBilgileri WHERE id = '" +
        dataGridView1.CurrentRow.Cells[0].Value.ToString() + "'";
        delcommand.CommandType = CommandType.Text;
        delcommand.ExecuteNonQuery();
        dataGridView1.Rows.RemoveAt(dataGridView1.SelectedCells[i].RowIndex);
        i--;
    }
}
connection.close();

如何使用复选框删除DataGridView中的多行

这里您正在解析Id,但随后不使用它。我猜应该是这样的。

int id = Convert.ToInt16(dataGridView1.SelectedRows[dataGridView1.SelectedCells[0].RowIndex].Cells[0].Value);
delcommand.Connection = connection;
delcommand.CommandText = string.Format("DELETE FROM TFirmaBilgileri WHERE id = {0}",id);

另一件事你没有打开连接。

应该像

using (var connection = new SqlConnection(myConnectionString))
{
    connection.Open();
    var command = connection.CreateCommand();
    command.CommandText = "...";
    command.ExecuteNonQuery();
} 

你把id用单引号括起来了,这很可能是不正确的:

delcommand.CommandText = "DELETE FROM TFirmaBilgileri WHERE id = '" +
    dataGridView1.CurrentRow.Cells[0].Value.ToString() + "'";

参数化您的查询以避免如下错误:

int id = Convert.ToInt16(dataGridView1.SelectedRows[dataGridView1.SelectedCells[0].RowIndex].Cells[0].Value);
delcommand.CommandText = "DELETE FROM TFirmaBilgileri WHERE id = @id";
delcommand.Parameters.AddWithValue("@id", id);

确保你也打开了连接。我在你的代码中没有看到这个

我还建议将您的SqlCommand封装在using块中,以便它被妥善处理。