Reputation: 942
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();
}
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");
I tried this:
grdCarritoAddons.Rows.RemoveAt(grdCarritoAddons.SelectedRows[0].Index);
But no go. Doesn't work in ASP. Thanks for any help :)
Current Code:
dt = HttpContext.Current.Session["DataTable"] as DataTable;
dt.Rows.RemoveAt(grdCarritoAddons.SelectedRow.RowIndex);
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.
Upvotes: 1
Views: 1635
Reputation: 460258
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
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();
Upvotes: 1