Question

I am working on an assignment where I need to create an XML file from a session. I am having a casting problem, and I am aware it is coming from the List, which is where the items in the cart are stored, but I am not sure how to fix it.

The button click is a Create XML button, and this is the exact error I am getting: Unable to cast object of type Utils.ShoppingCart' to type 'System.Collections.Generic.List1[CartItem]'.

Line 86: List<CartItem> cartItems = new List<CartItem>();

Line 87: cartItems = (List<CartItem>)Session["UserCart"];

Here is the code. Let me know if I need to provide more. I would greatly appreciate any feedback!

 protected void Button1_Click(object sender, EventArgs e)
 {
    ShoppingCart sCart = (ShoppingCart)Session["UserCart"];

    List<CartItem> cartItems = new List<CartItem>();
    cartItems = (List<CartItem>)Session["UserCart"];

    XmlWriterSettings sets = new XmlWriterSettings();
    sets.Indent = true;

    using (XmlWriter writer = XmlWriter.Create(Server.MapPath("~/items.xml"), sets))
    {

        writer.WriteStartDocument();
        writer.WriteStartElement("cartItems");

        foreach (CartItem i in cartItems)
        {
            writer.WriteStartElement("CartItem");
            writer.WriteElementString("ITEM_ID", i.ITEM_ID.ToString());
            writer.WriteElementString("ITEM_QUANTITY", i.ITEM_QUANTITY.ToString());

            writer.WriteEndElement();
        }

        writer.WriteEndElement();
        writer.Flush();
        writer.Close();

        Label1.Text = "XML written successfully!";

        Label2.Text = "<a href='DOM/cart.xml'> XML created successfully. </a>";
    }
}
Was it helpful?

Solution

This is just a guess, but as I put in my comment above, it looks like your first call to Session isn't creating an error (where you get the ShoppingCart instance from Session).

It looks like you're trying to retrieve the list of items from ShoppingCart. Since you already have the instance (in your first call to Session), all you need to do is access the property (if you have one) that contains the list of items in the cart, like this:

ShoppingCart sCart = (ShoppingCart)Session["UserCart"];

List<CartItem> cartItems = sCart.Items;

The above is based on ShoppingCart having a property called Items that returns a list of of CartItem.

The way you were doing it you were telling the compiler to get the ShoppingCart instance from Session and convert it to a List of CartItems, hence the error as I doubt ShoppingCart and CartItems are the same object :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top