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
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:
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.