未將對象引用設置到對象的實例"異常的原因

未將對象引用設置到對象的實例。

說明: 執行當前 Web 請求期間,出現未處理的異常。請檢查堆棧跟蹤信息,以瞭解有關該錯誤以及代碼中導致錯誤的出處的詳細信息。

異常詳細信息: System.NullReferenceException: 未將對象引用設置到對象的實例。

源錯誤:

行 70:             int gridviewQuantity = Convert.ToInt16(GridViewShoppingCartList.DataKeys[i].Value);//int.Parse(GridViewShoppingCartList.Rows[i].Cells[3].Text);
行 71:                 //if textboxquantity is changed and checkedRemove is checked!
行 73:             {
行 74:                 Label labelBookId = (Label)GridViewShoppingCartList.Rows[i].FindControl("LabelBookId");


源文件: f:/MyOnNetBookSell/ShoppingCarts.aspx.cs    行: 72

以下是代碼:

    protected void UpdateShoppingCartList()
    {
        ShoppingCart cart = new ShoppingCart();
        //obtain current user's shopping cart id
        string cartId = cart.GetShoppingCartID();
        //itarate through all rows with the shopping cart
        for (int i = 0; i < GridViewShoppingCartList.Rows.Count;i++ )
        {
            //
            TextBox textBoxQuantity = (TextBox)GridViewShoppingCartList.Rows[i].FindControl("TextBoxQuantity");

            CheckBox checkBoxRemove = (CheckBox)GridViewShoppingCartList.Rows[i].FindControl("TextBoxRemove"); //checkBoxRemove爲null值,因爲不存在TextBoxRemove控件
            int quantity;
            //try
            //{
            quantity = int.Parse(textBoxQuantity.Text);
            int gridviewQuantity = Convert.ToInt16(GridViewShoppingCartList.DataKeys[i].Value);//int.Parse(GridViewShoppingCartList.Rows[i].Cells[3].Text);
                //if textboxquantity is changed and checkedRemove is checked!
            if( quantity!=gridviewQuantity||checkBoxRemove.Checked==true)//運行到這裏就出錯
            {
                Label labelBookId = (Label)GridViewShoppingCartList.Rows[i].FindControl("LabelBookId");
                if (quantity == 0 || checkBoxRemove.Checked == true)
                {
                    cart.RemoveItems(cartId,Int32.Parse(labelBookId.Text));
                }
                else
                {
                    cart.UpdateItems(cartId,Int32.Parse(labelBookId.Text),quantity);
                }
            }
            //}
            //catch
          
            //{
            //   LabelError.Visible = true;
            //  LabelError.Text = "There has been a problem with one or more of your inputs.";
            //}

        }
  
    }

出錯原因:

在aspx頁面中並沒有id爲TextBoxRemove(原文中只有id爲CheckBoxRemove的控件),這就造成了 CheckBox checkBoxRemove = (CheckBox)GridViewShoppingCartList.Rows[i].FindControl("TextBoxRemove");中checkBoxRemove的值爲null,因此程序運行到此處時就會報:未將對象引用設置到對象的實例.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章