Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save an array of objects in a C# ASP.Net Sesssion?

I have in my C# ASP.Net program an array of objects that are filled in during a postback and I wish to recover them during the next postback. To this end I include the array declaration in the Default class definition which is saved thus:-

this.Session["This"] = this;

and recovered:-

Default saved_stuff = (Default) this.Session["This"];

This works fine for everything apart from:-

MyClass [] my_array;

When recovered, saved_stuff.my_array is always null.

MyClass is defined like this:-

public MyClass : ISerializable
{
    private string some_string;
    private double some_double;
    // some more simple members
    // Some getters and setters
    // ISerializable Implementation
}

I have tried making MyClass implement ISerializable but that doesn't make any difference. Does anyone know what I should be doing?

Edit to answer @Michael's question, I'm then doing things like...

for (int i = 0; i <= saved_stuff.my_array.GetUpperBound(0); i++)
{
    // blah blah
}

which is failing with "object reference is not set to an instance of an object". All the other member variables of Default are visible in saved_stuff when in debug.

like image 666
Brian Hooper Avatar asked Dec 14 '12 15:12

Brian Hooper


People also ask

Can array of objects be stored?

Storing Objects in an arrayYes, since objects are also considered as datatypes (reference) in Java, you can create an array of the type of a particular class and, populate it with instances of that class.

How do I save an array of objects in core data?

There are two steps to storing an array of a custom struct or class in Core Data. The first step is to create a Core Data entity for your custom struct or class. The second step is to add a to-many relationship in the Core Data entity where you want to store the array.

How do you store items in an array?

Storing Data in Arrays. Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.

How do you create an array in C?

To create an array, define the data type (like int ) and specify the name of the array followed by square brackets []. To insert values to it, use a comma-separated list, inside curly braces: int myNumbers[] = {25, 50, 75, 100}; We have now created a variable that holds an array of four integers.


1 Answers

You have to store your array data in its own session object:

MyClass[] my_array = //Something

Session["ArrayData"] = my_array;

Then retrieve it as:

var arrayData = (MyClass[])Session["ArrayData"];
like image 66
Azhar Khorasany Avatar answered Sep 18 '22 10:09

Azhar Khorasany