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

时间:2014-07-07 11:24:22

标签: c# datagridview delete-row

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

我无法找到错误的地方,但代码会抛出一个错误,说明没有定义参数。

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();

2 个答案:

答案 0 :(得分:0)

在这里,您正在解析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();
} 

答案 1 :(得分:0)

你用单引号括起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块中,以便妥善处理。