问题描述
我有一个小的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.
推荐答案
是的,此方法不存在,因为您可以看到此处.您应该改为修改数据源,然后再对网格进行数据绑定. DataRowCollection
具有 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中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!