locked
Object reference not set to an instance of an object RRS feed

  • Question

  • User458524405 posted

    Using Visual Studio 2012 ASP .NET 4.5 with C#

    0x800a139e - JavaScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: Object reference not set to an instance of an object.

    I'm receiving the above error for my shopping cart application and am not sure why.  Below are the page, code behind and class files.  Any Help would be greatly appreciated.

    The particular line I'm receiving the error on is below, which is located in the Order.aspx.cs code behind file. 

    • OrderItem orderItem = order[selectedItem.ProductID];

    Order.aspx

    <%

    @ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Order.aspx.cs" Inherits="Order" %>

    <

    asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

    <title>Mike's Shoes - Order</title>

    <link rel="stylesheet" href="App_Themes/blueprint/screen.css" type="text/css" media="screen, projection" />

    <link href="App_Themes/Blueprint/print.css" rel="stylesheet" type="text/css" media="print" />

    <!--[if lt IE 8]>

    <link href="App_Themes/Blueprint/ie.css" rel="stylesheet" type="text/css" media="screen, projection" />

    <![endif]-->

    <link rel="stylesheet" href="App_Themes/blueprint/StyleSheet.css" type="text/css" />

    </

    asp:Content>

    <

    asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

    <div class="content">

    <%

    --AJAX Update Panel--%>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">

    <Triggers>

    <asp:AsyncPostBackTrigger ControlID="ddlProductType" EventName="SelectedIndexChanged"/>

    <asp:AsyncPostBackTrigger ControlID="ddlProductColor" EventName="SelectedIndexChanged"/>

    <asp:AsyncPostBackTrigger ControlID="ddlProductSize" EventName="SelectedIndexChanged"/>

    <asp:AsyncPostBackTrigger ControlID="gwProductList" EventName="SelectedIndexChanged" />

    </Triggers>

    <ContentTemplate>

    <%

    --Product Type Drop Down Menu--%>

    <asp:DropDownList ID="ddlProductType" runat="server" DataSourceID="SqlDataSource1" DataTextField="ProductType" DataValueField="ProductType" OnSelectedIndexChanged="ddlProductType_SelectedIndexChanged" AutoPostBack="True"></asp:DropDownList>

    <asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString='<%$ ConnectionStrings:ConnectionString %>' SelectCommand="SELECT DISTINCT [ProductType] FROM [tblProducts]"></asp:SqlDataSource>

    <%

    --Product Color Drop Down Menu--%>

    <asp:DropDownList ID="ddlProductColor" runat="server" DataSourceID="SqlDataSource3" DataTextField="ProductColor" DataValueField="ProductColor" AutoPostBack="True" OnSelectedIndexChanged="ddlProductColor_SelectedIndexChanged"></asp:DropDownList>

    <asp:SqlDataSource runat="server" ID="SqlDataSource3" ConnectionString='<%$ ConnectionStrings:ConnectionString %>' SelectCommand="SELECT DISTINCT [ProductColor] FROM [tblProducts]"></asp:SqlDataSource>

    <%

    --Product Size Drop Down Menu--%>

    <asp:DropDownList ID="ddlProductSize" runat="server" DataSourceID="SqlDataSource4" DataTextField="ProductSize" DataValueField="ProductSize" OnSelectedIndexChanged="ddlProductSize_SelectedIndexChanged" AutoPostBack="True"></asp:DropDownList>

    <asp:SqlDataSource runat="server" ID="SqlDataSource4" ConnectionString='<%$ ConnectionStrings:ConnectionString %>' SelectCommand="SELECT DISTINCT [ProductSize] FROM [tblProducts]"></asp:SqlDataSource>

    <%

    -- Gridview--%>

    <asp:GridView ID="gwProductList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource2" DataKeyNames="ProductID,ProductImage" OnSelectedIndexChanged="gwProductList_SelectedIndexChanged" SelectedIndex="1" SelectedRowStyle-Font-Bold="True">

    <Columns>

    <asp:BoundField DataField="ProductID" SortExpression="ProductID" Visible="False"></asp:BoundField>

    <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName"></asp:BoundField>

    <asp:BoundField DataField="ProductType" HeaderText="ProductType" SortExpression="ProductType"></asp:BoundField>

    <asp:BoundField DataField="ProductColor" HeaderText="ProductColor" SortExpression="ProductColor"></asp:BoundField>

    <asp:BoundField DataField="ProductSize" HeaderText="ProductSize" SortExpression="ProductSize"></asp:BoundField>

    <asp:BoundField DataField="ProductPrice" HeaderText="ProductPrice" SortExpression="ProductPrice"></asp:BoundField>

    <asp:BoundField DataField="ProductImage" HeaderText="ProductImage" SortExpression="ProductImage" Visible="False"></asp:BoundField>

    <asp:CommandField ShowSelectButton="True" ButtonType="Button" SelectText="Select" />

    </Columns>

    </asp:GridView>

    <asp:SqlDataSource runat="server" ID="SqlDataSource2" ConnectionString='<%$ ConnectionStrings:ConnectionString %>' SelectCommand="SELECT * FROM [tblProducts] WHERE (([ProductType] = @ProductType) AND ([ProductColor] = @ProductColor) AND ([ProductSize] = @ProductSize))">

    <SelectParameters>

    <asp:ControlParameter ControlID="ddlProductType" PropertyName="SelectedValue" Name="ProductType" Type="String"></asp:ControlParameter>

    <asp:ControlParameter ControlID="ddlProductColor" PropertyName="SelectedValue" Name="ProductColor" Type="String"></asp:ControlParameter>

    <asp:ControlParameter ControlID="ddlProductSize" PropertyName="SelectedValue" Name="ProductSize" Type="Int32"></asp:ControlParameter>

    </SelectParameters>

    </asp:SqlDataSource>

    <%

    --Product Image Displayed When Selected--%>

    <asp:Image ID="imgProduct" runat="server" />

    <asp:Label ID="lblQuantity" runat="server" Text="Quantity"></asp:Label>

    <asp:TextBox ID="txtQuantity" runat="server"></asp:TextBox>

    <asp:Button ID="btnAdd" runat="server" Text="Add to Cart" OnClick="btnAdd_Click" />

    <asp:Button ID="btnCart" runat="server" Text="Go to Cart" />

    <asp:Button ID="btnCheckOut" runat="server" Text="Checkout" />

    </ContentTemplate>

    </asp:UpdatePanel>

    </div>

    </

    asp:Content>

    Order.aspx.cs

    using

    System;

    using

    System.Collections.Generic;

    using

    System.Linq;

    using

    System.Web;

    using

    System.Web.UI;

    using

    System.Web.UI.WebControls;

    public

    partial class Order : System.Web.UI.Page

    {

    private Product selectedItem;

    protected void Page_Load(object sender, EventArgs e)

    {

    UnobtrusiveValidationMode = System.Web.UI.

    UnobtrusiveValidationMode.None;

    //GridViewRow selectRow = gwProductList.SelectedRow;

    //selectedItem = this.GetSelectedItem();

    }

    protected void ddlProductType_SelectedIndexChanged(object sender, EventArgs e)

    {

    imgProduct.ImageUrl =

    "";

    }

    protected void ddlProductColor_SelectedIndexChanged(object sender, EventArgs e)

    {

    imgProduct.ImageUrl =

    "";

    }

    protected void ddlProductSize_SelectedIndexChanged(object sender, EventArgs e)

    {

    imgProduct.ImageUrl =

    "";

    }

    protected void gwProductList_SelectedIndexChanged(object sender, EventArgs e)

    {

    imgProduct.ImageUrl =

    "../Images/" + gwProductList.SelectedDataKey[1];

    selectedItem =

    this.GetSelectedItem();

    }

    private Product GetSelectedItem()

    {

    GridViewRow selectRow = gwProductList.SelectedRow;

    Product newItem = new Product();

    newItem.ProductID = gwProductList.SelectedValue.ToString();

    newItem.ProductName = selectRow.Cells[1].Text;

    newItem.ProductType = selectRow.Cells[2].Text;

    newItem.ProductColor = selectRow.Cells[3].Text;

    newItem.ProductSize = selectRow.Cells[4].Text;

    newItem.ProductPrice =

    Convert.ToDecimal(selectRow.Cells[5].Text);

    return newItem;

    }

    protected void btnAdd_Click(object sender, EventArgs e)

    {

    OrderItemList order = OrderItemList.GetOrder();

    OrderItem orderItem = order[selectedItem.ProductID];

    if (orderItem == null)

    {

    order.AddItem(selectedItem,

    Convert.ToInt32(txtQuantity.Text));

    }

    else

    {

    orderItem.AddQuantity(

    Convert.ToInt32(txtQuantity.Text));

    }

    Response.Redirect(

    "Cart.aspx");

    }

    }

    OrderItemList.cs

    using

    System;

    using

    System.Collections.Generic;

    using

    System.Web;

    using

    System.Linq;

    ///

    <summary>

    ///

    Summary description for OrderItemList

    ///

    </summary>

    public

    class OrderItemList

    {

    private List<OrderItem> orderItems;

    public OrderItemList()

    {

    orderItems =

    new List<OrderItem>();

    }

    public int Count

    {

    get { return orderItems.Count; }

    }

    public OrderItem this[int index]

    {

    get { return orderItems[index]; }

    set { orderItems[index] = value; }

    }

    public OrderItem this[string id]

    {

    get

    {

    foreach (OrderItem c in orderItems)

    if (c.Product.ProductID == id) return c;

    return null;

    }

    }

    public static OrderItemList GetOrder()

    {

    OrderItemList order = (OrderItemList)HttpContext.Current.Session["Cart"];

    if (order == null)

    HttpContext.Current.Session["Cart"] = new OrderItemList();

    return (OrderItemList)HttpContext.Current.Session["Cart"];

    }

    public void AddItem(Product product, int quantity)

    {

    OrderItem c = new OrderItem(product, quantity);

    orderItems.Add(c);

    }

    }

    OrderItem.cs

    ///

    <summary>

    ///

    Summary description for OrderItem

    ///

    </summary>

    public

    class OrderItem

    {

    public

    OrderItem(){}

    public

    OrderItem(Product product, int quantity)

    {

    this.Product = product;

    this.Quantity = quantity;

    }

    public

    Product Product { get; set; }

    public

    int Quantity { get; set; }

    public

    void AddQuantity(int quantity)

    {

    this.Quantity += quantity;

    }

    public

    string Display()

    {

    string displayString = Product.ProductName + " (" + Quantity.ToString()

    +

    " at " + Product.ProductPrice.ToString("c") + " each)";

    return displayString;

    }

    }

    Saturday, December 6, 2014 1:12 AM

Answers

  • User281315223 posted

    A Null Reference Exception is thrown when you attempt to reference a property, method or field from a null object. You can generally avoid these by adding explicit checks to ensure that your object exists when it is referenced.

    In this case, you have a private selectedItem property define on your page :

    private Product selectedItem;

    And you mentioned that when your AddClick event is triggered, that you are receiving a null reference exception on the following line :

    OrderItem orderItem = order[selectedItem.ProductID];

    I don't see anything within your Page_Load event that actually sets the value of your selectedItem property (although it looks like you had something and commented it out). But if that is the case, then you have to at least perform an event that will set it prior to clicking the Add button that is triggering your event. So you have a few options here, you could either instantiate your property within your Page_Load event :

    protected void Page_Load(object sender, EventArgs e)
    {
           UnobtrusiveValidationMode = System.Web.UI.
           UnobtrusiveValidationMode.None;
    
           // On your initial load, instantiate your selectedItem
           if(!IsPostBack)
           {
                 selectedItem = this.GetSelectedItem();
           }  
    }

    This would ensure that your value is actually set prior to any other operations. Otherwise, you could explicitly check and ensure that your value isn't null (and if it is either attempt to set it or display an error to the user) :

    protected void btnAdd_Click(object sender, EventArgs e)
    {
             OrderItemList order = OrderItemList.GetOrder();
    
             // Check if you have a selectedItem
             if(selectedItem == null)
             {
                   // You don't have one, attempt to set it (you could also display an error to the user here)
                   selectedItem = this.GetSelectedItem();
             }
    
             OrderItem orderItem = order[selectedItem.ProductID];
             
             // Other code omitted for brevity
    }

    The best way to resolve this issue would be to place some breakpoints throughout your code and monitor the value of your selectedItem property to ensure that it is being set as you would expect (and isn't referenced when it might not be set).

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, December 6, 2014 8:13 AM