简体   繁体   English

使用复选框Asp.net从gridview删除不起作用

[英]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. 我正在尝试使用复选框从gridview中删除项目,但是我有此操作并删除了每个项目。

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' 运算符“-”不能应用于“方法组”和“ int”类型的操作数
  • Cannot apply indexing with [] to an expression of type ' 无法将[]的索引应用于类型为'的表达式
  • GridViewRowCollection' does not contain a definition for 'RemoveAt' GridViewRowCollection”不包含“ 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?) 并且找不到扩展方法'RemoveAt'接受类型为'GridViewRowCollection'的第一个参数(您是否缺少using指令或程序集引用?)

You have two major issues: 您有两个主要问题:

1) GridView.SelectedRow is not a collection property, it is a standard property. 1) GridView.SelectedRow不是集合属性,而是标准属性。 Therefore, you can neither use Count property nor array index on it. 因此,您不能在其上使用Count属性或数组索引。 To iterate between rows with for loop, use GridView.Rows.Count property instead. 要使用for循环在行之间进行迭代,请改用GridView.Rows.Count属性。

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 . 2) GridViewRowCollection方法中不存在RemoveAt方法,您可以在此处看到。 You need to delete rows with selected index from data source and rebind to GridView afterwards. 您需要从数据源中删除具有选定索引的行,然后再重新绑定到GridView

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循环来迭代网格行,并对每个复选框的Checked属性进行检查,如下例所示。

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 使用复选框删除gridview中的多行

Delete specific row in dynamically generated gridview 删除动态生成的gridview中的特定行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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