Solved

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

Posted on 2003-12-04
7
102,068 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 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…

623 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