title: Adding Items to the Grid View: Index was out of range exception
body: <p>I'm trying to add items in a GridView using the following code but it is throwing the exception: </p>
  
  <pre><code>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.
  </code></pre>
  
  <p>Here is my code:</p>
  
  <pre><code> 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&lt;int&gt; ProductsInCart = (List&lt;int&gt;)Session["Cart"];
           if (ProductsInCart == null)
           {
               ProductsInCart = new List&lt;int&gt;();
           }
           ProductsInCart.Add(ProductID);
           Session["Cart"] = ProductsInCart;
       }
   }
  </code></pre>