0

How can I delete multiple rows in a DataGridView using a CheckBox?

I could not find where I do mistakes, but the code throws an error which explains not defined the parameters.

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();
Unihedron
  • 10,251
  • 13
  • 53
  • 66

2 Answers2

0

Here you are parsing Id but then not using it. My guess it should be like this.

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

Another thing you are not opening connection.

it should be something like

using (var connection = new SqlConnection(myConnectionString))
{
    connection.Open();
    var command = connection.CreateCommand();
    command.CommandText = "...";
    command.ExecuteNonQuery();
} 
Matas Vaitkevicius
  • 49,230
  • 25
  • 212
  • 228
0

You're surrounding the id in single quotes, which most likely is incorrect:

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

Parameterize your query to avoid errors like these:

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

Make sure you're opening your connection too. I don't see that in your code.

I'd also suggest enclosing your SqlCommand in a using block so that it's disposed properly.

Grant Winney
  • 61,140
  • 9
  • 100
  • 152