Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2003-12-04
7
Medium Priority
?
102,082 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 600 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 18

Accepted Solution

by:
testn earned 200 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…

705 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