0

I'm trying to use checkbox to remove items from a gridview but I had this and removes every item.

DataTable data = (DataTable)(GridView2.DataSource);
            data.Rows.RemoveAt(GridView2.Rows.Count - 1);
            data.AcceptChanges();
            GridView2.DataSource = dt;
            GridView2.DataBind();

Then I'm trying this

for (int i = GridView2.SelectedRow.Count - 1; -1 < i; i--)
        {
            object objChecked = GridView2.SelectedRow[i].Cells[0].Value;
            if ((objChecked != null) && !(bool)objChecked)
            {
                GridView2.Rows.RemoveAt(i);
            }
        }

These are the errors I'm getting

  • Operator '-' cannot be applied to operands of type 'method group' and 'int'
  • Cannot apply indexing with [] to an expression of type '
  • GridViewRowCollection' does not contain a definition for 'RemoveAt'
    and no extension method 'RemoveAt' accepting a first argument of type 'GridViewRowCollection' could be found(are you missing a using directive or an assembly reference?)

1 Answer 1

0

You have two major issues:

1) GridView.SelectedRow is not a collection property, it is a standard property. Therefore, you can neither use Count property nor array index on it. To iterate between rows with for loop, use GridView.Rows.Count property instead.

for (int i = 0; i < GridView2.Rows.Count; i++)
{
    // do something
}

2) RemoveAt method doesn't exist in GridViewRowCollection method, you can see that here. You need to delete rows with selected index from data source and rebind to GridView afterwards.

Hence, use a foreach loop to iterate grid rows and put a check against Checked property of each checkbox as given by example below.

foreach (GridViewRow row in GridView2.Rows)
{
    CheckBox chk = row.FindControl("CheckBoxName") as CheckBox;
    if (chk != null && chk.Checked)
    {
        // delete from data source (e.g. DataTable), not GridView row
        dt.Rows.RemoveAt(row.RowIndex);

        // you can execute delete query against DB here
    }
}

// rebind the grid
GridView2.DataSource = dt;
GridView2.DataBind();

Similar issues:

delete multiple rows in gridview using checkboxes

Delete specific row in dynamically generated gridview

Sign up to request clarification or add additional context in comments.

2 Comments

ok thanks for this info however when I add this CheckBox chk = row.FindControl("CheckBoxName") as CheckBox; and check a row it is saying that it is null
And it still removing all the items that weren't check and if I check all it says that there's no row at position 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.