Solved

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

Posted on 2003-12-04
7
102,050 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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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 video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

837 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