Solved

Saving an array in Session in C#

Posted on 2004-09-16
9
2,644 Views
Last Modified: 2008-02-01
I have an array that I need to save and retrieve as a session variable.

I initialize and save the array as follows:  
    g_Move_Direction= new int[40];
    for (i=0; i<40; i++)
        {g_Move_Direction[i] =2;}
    this.Session["Move_Direction"]=g_Move_Direction;

Later I retrieve the array as follows:
    int[] g_Move_Direction = (int[]) this.Session["Move_Direction"];
   
When I try and save a new value to the array using,      
     g_Move_Direction[g_segment_count]= Convert.ToInt32(this.radio_Direction.SelectedValue);

I get the following error page: [Note I've verified that radio_Direction.SelectedValue is 1 when attempting to save the new value.]
*******************************************************************************************
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 411:      segment_type=this.radio_SegmentType.SelectedValue;
Line 412:      //Save segment type, move direction & axis
Line 413:      g_Move_Direction[g_segment_count]= Convert.ToInt32(this.radio_Direction.SelectedValue);
Line 414:      g_Segment_Type[g_segment_count]=segment_type;
Line 415:      g_Segment_Axis[g_segment_count]=this.ddlAxialForceDirection.SelectedValue;
 
Source File: c:\vsprojects\manhattanapps\actuatordesignersolution\actuatordesigner\complex_move.aspx.cs    Line: 413
Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
   Actuator1.Complex_Move.btnSaveSegment_Click(Object sender, EventArgs e) in c:\vsprojects\manhattanapps\actuatordesignersolution\actuatordesigner\complex_move.aspx.cs:413
   System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e)
   System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
   System.Web.UI.Page.ProcessRequestMain()

 *******************************************************************************************

Am I saving/retrieving it correctly?

0
Comment
Question by:RosanneParnell
  • 5
  • 4
9 Comments
 
LVL 4

Expert Comment

by:vigrid
ID: 12076639
Please review and check if these are not null while reading from session:
g_Move_Direction,
g_segment_count

Tell me the exact values these have in line 413 in file "complex_move.aspx.cs" and tell me their exact types too.
0
 

Author Comment

by:RosanneParnell
ID: 12076687
g_Move_Direction is of type int[40] and at this point  has <undefined value> in the watch list

g_segment_count is of type int and has the value of 0 (zero).
0
 
LVL 4

Expert Comment

by:vigrid
ID: 12076721
It seems that something happened with the g_Move_Direction meanwhile. Please check if you really got it back correct in line:

int[] g_Move_Direction = (int[]) this.Session["Move_Direction"];

Another thing that pops into my mind is that you can have another variable declared in another scope and you use two different variables, no matter that they have same names?
0
 

Author Comment

by:RosanneParnell
ID: 12076830
I'm new to .Net and C# so the scope is a bit confusing to me right now.

I have g_Move_Direction declared here:
namespace Actuator1
{
      /// <summary>
      /// Summary description for Complex_Move.
      /// </summary>
      public class Complex_Move : System.Web.UI.Page
      {
                   protected System.Web.UI.HtmlControls.HtmlForm Form1;
                   .
                   .
                   .
                   int[] g_Move_Direction;

and then in the Page_Load routine (for the first time through the page only - postback=false) I initialize it and save it:
    g_Move_Direction= new int[40];
    for (i=0; i<40; i++)
        {g_Move_Direction[i] =2;}
    this.Session["Move_Direction"]=g_Move_Direction;


on a post back to the page I retrieve it using:
  int[] g_Move_Direction = (int[]) this.Session["Move_Direction"];

Upon retrieving it (prior to attempting to store a value in it) I did confirm that the array is still set to all 2's.
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:RosanneParnell
ID: 12076868
Am I defining this variable (g_Move_Direction) in the wrong spot and then the code doesn't see it in the page functions?
0
 
LVL 4

Assisted Solution

by:vigrid
vigrid earned 500 total points
ID: 12077082
Yep, you made a mistake. You declared the variable again so it put the old variable out of scope:

Think of your variable (field) in the class as:
Actuator1.Complex_Move.g_Move_Direction - you declared it in the class

And about the variable you declared in method as:
Actuator1.Complex_Move.Page_Load.g_Move_Direction

As you can see these two are different, but C# sees the one you have declared in the Page_Load method as the g_Move_Direction. So it's considering the scope.

What you need to do is to get rid of "int[]" in front of the line you read the variables from session:
g_Move_Direction = (int[]) this.Session["Move_Direction"];

You only need to do that, because you already have declared the array in the class.

BTW, please take a look on some .NET and C# coding and naming conventions. They will help you in the future. I guess that the "g_" prefix was supposed to mean "global", and that is an obsolete term in C#. Another very nice tool that will help you maintain your code high quality is FxCop (http://www.gotdotnet.com/team/fxcop/).

HTH
0
 
LVL 4

Accepted Solution

by:
vigrid earned 500 total points
ID: 12077163
I think I made a little mistake here and maybe some of the fully-qualified variable names won't match the ones you have in your code, but I hope that the concept of scope is much clearer for you. Just to be sure:

namespace MyNamespace
{
  class MyClass
  {
    private int myVariable = 1;

    public void Test1()
    {
      Console.WriteLine(myVariable);
    }

    public void Test2()
    {
      int myVariable = 2;
      Console.WriteLine(myVariable);
    }

    public static void Main()
    {
      Test1(); // will write 1 (MyNamespace.MyClass.myVariable)
      Test2(); // will write 2 (MyNamespace.MyClass.Test2.myVariable)
      Test1(); // will write 1 (MyNamespace.MyClass.myVariable)
    }
  }
}

After the call to the Test2 method, that method worked on its own myVariable variable and changed that variable's value, not the one declared in the class.
0
 
LVL 4

Expert Comment

by:vigrid
ID: 12077182
And if you would add another method:

public void Test3()
{
  myVariable = 3;
  Console.WriteLine(myVariable);
}

and changed the Main:

public static void Main()
{
  Test1(); // will write 1 (MyNamespace.MyClass.myVariable)
  Test2(); // will write 2 (MyNamespace.MyClass.Test2.myVariable)
  Test1(); // will write 1 (MyNamespace.MyClass.myVariable)
  Test3(); // will write 3 (MyNamespace.MyClass.myVariable!!!, because no variable of the same name is declared)
  Test1(); // will write 3 (MyNamespace.MyClass.myVariable)
}
0
 

Author Comment

by:RosanneParnell
ID: 12077287
Thanks! That works!
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now