Solved

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

Posted on 2003-12-04
7
102,032 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
Comment Utility
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
Comment Utility
That didn't get it.  I appreciate your reply.

Brian
0
 

Assisted Solution

by:RuiSousa
RuiSousa earned 150 total points
Comment Utility
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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 18

Accepted Solution

by:
testn earned 50 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

763 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

9 Experts available now in Live!

Get 1:1 Help Now