Solved

Object reference not set to an instance of an object. - ASP.NET using C# codebehind

Posted on 2003-12-04
7
102,045 Views
Last Modified: 2011-08-18
I am getting the following compiler erro while using the following code behind file in C#

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

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
   MainMenu.Page_Load(Object sender, EventArgs e) +30
   System.EventHandler.Invoke(Object sender, EventArgs e) +0
   System.Web.UI.Control.OnLoad(EventArgs e) +67
   System.Web.UI.Control.LoadRecursive() +35
   System.Web.UI.Page.ProcessRequestMain() +731


<code>
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Security;

public class MainMenu : System.Web.UI.Page {
   
    protected Label lblTitle;
    protected DataGrid dataGrid1;
   
    protected bool Access;

    public MainMenu() {
      Page.Init += new System.EventHandler(Page_Init);
    }

    private void Page_Init(object sender, EventArgs e){
      InitializeComponent();
    }

    private void InitializeComponent(){
      this.Load += new System.EventHandler(this.Page_Load);
    }

    private void Page_Load(object sender, System.EventArgs e){
      string AccessLevel = Session["AccessLevel"].ToString();
      MainPageData(AccessLevel);
    }
   
    protected void MainPageData(string ALevel) {
     
      Access = ALevel.Equals("admin");
      if(Access){
        lblTitle.Text = "Legislative Tracking Administrator.";
        lblTitle.Visible = true;

        string connectionString = "server=server; uid=username; " +
          "pwd=password; database=database";

        SqlConnection connection = new SqlConnection(connectionString);
        connection.Open();

        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        string sql = "SELECT * FROM tblLaw WHERE Status <> 'C'";
        command.CommandText = sql;

        SqlDataAdapter dataAdapter = new SqlDataAdapter();
        dataAdapter.SelectCommand = command;
        dataAdapter.TableMappings.Add("Table", "tblLaw");

        DataSet dataSet = new DataSet();
        dataAdapter.Fill(dataSet);
        dataGrid1.DataSource=dataSet.Tables[0];
        dataGrid1.DataBind();
      }
      else{
        lblTitle.Text = "Legislative Tracking.";
        lblTitle.Visible = true;
      }
    }
}
</code>
0
Comment
Question by:bjburke
7 Comments
 
LVL 7

Expert Comment

by:jj819430
ID: 9878511
try this.... I don't think it is the problem, but it may be.

dataGrid1.DataSource=dataSet.Tables[0].defaultview;

0
 

Author Comment

by:bjburke
ID: 9878686
That didn't get it.  I appreciate your reply.

Brian
0
 

Assisted Solution

by:RuiSousa
RuiSousa earned 150 total points
ID: 9878863
Make sure the Session Key (Session["AccessLevel"]) exists. If it doesn't you will get that error. This may work:

if (Session.Keys.Count == 0)
    string AccessLevel = "";    
else
    string AccessLevel = Session["AccessLevel"].ToString();
   

But its not a prety solution....


0
ScreenConnect 6.0 Free Trial

At ScreenConnect, partner feedback doesn't fall on deaf ears. We collected partner suggestions off of their virtual wish list and transformed them into one game-changing release: ScreenConnect 6.0. Explore all of the extras and enhancements for yourself!

 
LVL 18

Accepted Solution

by:
testn earned 50 total points
ID: 9878887
change

string AccessLevel = Session["AccessLevel"].ToString();

to

string AccessLevel = Convert.ToString(Session["AccessLevel"]);

and change

     Access = ALevel.Equals("admin");
      if(Access){

to
     if(ALevel=="admin") {
0
 

Author Comment

by:bjburke
ID: 9882776
I've implemented both of your solutions.  The piece of code that is still giving me a hard time is the Page_Load method.  This is what happens.  Thanks for both your responses.

If I use the code below this error message, I get a compiler error.

Compiler Error Message: CS0103: The name 'AccessLevel' does not exist in the class or namespace 'MainMenu'

Source Error:

Line 36:         string AccessLevel = Convert.ToString(Session["AccessLevel"]);
Line 37:       }
Line 38:       MainPageData(AccessLevel); <---Error on this line.
Line 39:     }
Line 40:    

private void Page_Load(object sender, System.EventArgs e){
  if (Session.Keys.Count == 0){
    string AccessLevel = "";
  }
  else{
    string AccessLevel = Convert.ToString(Session["AccessLevel"]);
  }
  MainPageData(AccessLevel);
}

If I delare the string outside of the if, I get this compiler error.

Compiler Error Message: CS1513: } expected

Source Error:

Line 29:     }
Line 30:
Line 31:     private void Page_Load(object sender, System.EventArgs e){ <---Error on this line
Line 32:       public string AccessLevel;
Line 33:       if (Session.Keys.Count == 0){

private void Page_Load(object sender, System.EventArgs e){
  public string AccessLevel;
  if (Session.Keys.Count == 0){
    AccessLevel = "";
  }
  else{
    AccessLevel = Convert.ToString(Session["AccessLevel"]);
  }
  MainPageData(AccessLevel);
}
0
 

Author Comment

by:bjburke
ID: 9882906
I used this code.  All I did was take out the public access modifier.   I was getting the original error I posted because the session object didn't exist.   It looks like my session variable from the previous page isn't getting set.  Another question all together.  Thanks for your help.

private void Page_Load(object sender, System.EventArgs e){
  string AccessLevel;
  if (Session.Keys.Count == 0){
    AccessLevel = "";
  }
  else{
    AccessLevel = Convert.ToString(Session["AccessLevel"]);
  }
  MainPageData(AccessLevel);
}
0
 
LVL 18

Expert Comment

by:testn
ID: 9898605
You didn't have to implement the first solution offered by RuiSousa. It should work by just implementing the second solution.
It is so because the solutions aren't complement to each other.
0

Featured Post

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

773 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