未将对象引用设置到对象的实例。
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。
源错误:
|
源文件: 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,因此程序运行到此处时就会报:未将对象引用设置到对象的实例.