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

查看:77
本文介绍了删除动态生成的gridview中的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的GridView,可以容纳某些物品.这是在用户单击项目后生成gridview的代码:

I have a small GridView that will hold certain items. This is the code that generates the gridview after a user clicks an item:

 if (grdCarritoAddons.Rows.Count == 0)
        {

            dt.Columns.Add(new DataColumn("Name", typeof(System.String)));
            dt.Columns.Add(new DataColumn("Price", typeof(System.String)));
        }
        else
        {
            dt = HttpContext.Current.Session["DataTable"] as DataTable;
        }
        Session["DataTable"] = dt;

        DataRow dr1 = dt.NewRow();
        dr1[0] = AddonName.ToString();
        dr1[1] = Convert.ToDecimal(PriceAddon);
        dt.Rows.Add(dr1);
        grdCarritoAddons.DataSource = dt;
        grdCarritoAddons.DataBind();

    }

现在,我需要用户能够选择一项并删除特定项.在ASPX页面中,我已经添加了Delete命令,并在代码中和GridView属性上创建了一个空的RowDeleting方法.它没有用,我想出了一个虽然可行但不是我需要做的解决方案.基本上,它会擦除​​整个DataTable.

Now I need a user to be able to select an item and delete a specific one. In the ASPX page I already added the Delete Command and created an empty RowDeleting method in code and on the GridView properties. It isn't working, and I came up with a solution that somewhat works but isn't what I need to do. It basically wipes out the whole DataTable.

            //grdCarritoAddons.DataSource = dt;
        //grdCarritoAddons.DataBind();
        //Session["DataTable"] = dt;
        //Session.Remove("Total");

我尝试过:

grdCarritoAddons.Rows.RemoveAt(grdCarritoAddons.SelectedRows[0].Index);

但是不行.在ASP中不起作用.感谢您的帮助:)

But no go. Doesn't work in ASP. Thanks for any help :)

当前代码:

            dt = HttpContext.Current.Session["DataTable"] as DataTable;
            dt.Rows.RemoveAt(grdCarritoAddons.SelectedRow.RowIndex);

但是它抛出的Object引用未设置为对象异常的实例.如果我放置一个IF来检查该行是否为空,它将根本不会执行...但是数据显然不是空的.

But its throwing an Object reference not set to an instance of an object exception. If I put an IF to check if the row is null it won't execute at all... but the data is obviously not empty.

推荐答案

这是错误:'System.Web.UI.WebControls.GridViewRowCollection' 不包含"RemoveAt"的定义,也没有扩展方法 'RemoveAt'接受类型的第一个参数 可以找到"System.Web.UI.WebControls.GridViewRowCollection"

This is the Error: 'System.Web.UI.WebControls.GridViewRowCollection' does not contain a definition for 'RemoveAt' and no extension method 'RemoveAt' accepting a first argument of type 'System.Web.UI.WebControls.GridViewRowCollection' could be found

是的,此方法不存在,因为您可以看到 RemoveAt方法.

Yes, this method does not exist as you can see here. You should modify the datasource instead and databind the grid afterwards. DataRowCollection has a RemoveAt method.

dt.Rows.RemoveAt(grdCarritoAddons.SelectedRow.RowIndex);
grdCarritoAddons.DataSource = dt;
grdCarritoAddons.DataBind();

这篇关于删除动态生成的gridview中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆