我嘗試使用下面的代碼添加在GridView的項目,但它拋出異常:將項目添加到網格視圖:索引超出範圍例外
An exception of type 'System.ArgumentOutOfRangeException' occurred in 'mscorlib.dll' but was not handled in user code
Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
這裏是我的代碼:
protected void GridViewProduct_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToCart")
{
int RowClicked = Convert.ToInt32(e.CommandArgument);
int ProductID = Convert.ToInt32(GridViewProduct.DataKeys[RowClicked].Value);
List<int> ProductsInCart = (List<int>)Session["Cart"];
if (ProductsInCart == null)
{
ProductsInCart = new List<int>();
}
ProductsInCart.Add(ProductID);
Session["Cart"] = ProductsInCart;
}
}
哪一行會引發異常? – Dmitry
GridViewProduct.DataKeys [RowClicked]在該行中顯示可疑。你有沒有檢查過DataKeys是什麼,以及rowclicked有什麼? – TYY
int ProductID = Convert.ToInt32(GridViewProduct.DataKeys [RowClicked] .Value); 在此行收到異常! – user3470196