简体   繁体   中英

Delete from gridview using checkbox Asp.net not working

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM