将项添加到网格视图:索引超出范围异常

时间:2014-03-27 19:56:54

标签: c# exception gridview

我正在尝试使用以下代码在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;
     }
 }

1 个答案:

答案 0 :(得分:0)

哪一行抛出此异常?在转换为List之前,您应该检查并确保Session [&#34; Cart&#34;]不为null。您可能失去该会话对象的原因很多。还要确保RowClicked不为null,因为这也可能导致异常。 在此事件的开头设置断点(如果(e.CommandName ==&#34; AddToCart&#34;)),然后逐步检查每行代码以查找空引用。 举个例子:

if(Session["Cart"] != null)
  {
     // Then cast to list
  }