1

I have a master page that set ups some variables that I want to use across the site..

protected void Page_Load(object sender, EventArgs e)
{
    //Get users name from AD
    str_DomainName = HttpContext.Current.User.Identity.Name;
    str_CurrentLogin = str_DomainName.Substring(5);

    //Display current user information
    DirectorySearcher search = new DirectorySearcher("LDAP://DCHS");
    search.Filter = String.Format("(SAMAccountName={0})", str_CurrentLogin);
    SearchResult result = search.FindOne();
    DirectoryEntry entry = result.GetDirectoryEntry();
    lbl_CurrentUser.Text = result.Properties["givenName"][0].ToString() + ' ' + result.Properties["sn"][0].ToString();

    // Get SID
    IntPtr logonToken = WindowsIdentity.GetCurrent().Token;
    WindowsIdentity windowsId = new WindowsIdentity(logonToken);

    //Set session variabls
    this.CurrentFirstName = result.Properties["givenName"][0].ToString();
    //this.CurrentEmail = result.Properties["mail"][0].ToString();
    //this.CurrentSID = windowsId.User.ToString();
    //this.CurrentUserName = str_CurrentLogin;
    //this.CurrentFullName = lbl_CurrentUser.Text;
    //this.CurrentDomain = str_DomainName;
    this.Session.Add("currentEmail", result.Properties["mail"][0].ToString());
}

public String CurrentFirstName
        {
            get { return (String)ViewState["currentFirstName"]; }
            set { ViewState["currentFirstName"] = value; }
        }

I then call them in my defalut.aspx page as follows:

protected void Page_PreRender(object sender, EventArgs e)
        {
            //try
            //{
                lbl_FullName.Text = Master.CurrentFullName;
                lbl_SID.Text = Master.CurrentSID;
                testLabel.Text = Master.CurrentEmail;
            //}
            //catch (Exception ex)
            //{ }
        }

This works fine.. If I however navigate away from the default page, then I get the following error..

Object reference not set to an instance of an object.

One the lbl_FullName.Text = Master.CurrentFullName; line

If I uncomment the try catch then it works fine, but I don't believe that this is the correct method of avoiding the fault..

I'm only new to ASP, so be nice..

EDIT:

The variabes are being set in Master.cs as follows.

public String CurrentUserName
        {
            get { return (String)ViewState["currentUserName"]; }
            set { ViewState["currentUserName"] = value; }
        }
Matt
  • 4,140
  • 9
  • 40
  • 64
  • It may depend on the order the various events are processed (i.e. maybe you're trying to read a value from the page before it's been set in the master page). Look at [this](http://msdn.microsoft.com/en-us/library/dct97kc3.aspx) and try checking the sequence of events – Paolo Falabella Mar 18 '11 at 00:50
  • what is the Master variable? Does it get set on other pages or just on default? – Spikolynn Mar 18 '11 at 00:52
  • See my edit for how I'm generating the variables – Matt Mar 18 '11 at 01:22
  • See http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net for the underlying reason: "because you didn't initialize the variables". – John Saunders Mar 18 '11 at 01:36

2 Answers2

1

A few questions:

  • Which side of the expression is generating the error: this.lbl_FullName or this.Master?
  • If it's the former, then there's something funky going on in your page.aspx.designer.cs file. Make sure the label control has been declared in there (this file is automatically generated by visual studio, but can sometimes not update properly). You should see a single line like this:

protected global::System.Web.UI.WebControls.Label lbl_FullName;

  • If it's the this.Master property then your page is obviously not referencing your masterpage. Check the page directive (the top line of your .aspx file) and make sure that the DynamicMasterPage value is set and that the path is correct.

On a design note, the masterpage isn't the best place to "store variables". The masterpage should literally just be used to initialise the common parts of the page across your site.

If you need to gather information from a user and use it across several pages, use session variables. This is a method of storing objects "in memory" for as long as the user's browser is open.

Items can be added to the session as follows:

this.Session.Add("fullName", fullName);

Items can then be retrieved later from any other page / usercontrol in your site as follows:

string fullName = (string)this.Session["fullName"];
  • How do I tell which side the error is coming from? Also, do you suggest I shift all my user grabbing code to the default page then? – Matt Mar 18 '11 at 01:22
  • Also, where do you suggest I put that code you mentioned? In the Default.aspx.cs? – Matt Mar 18 '11 at 03:09
  • From looking at your code though, I'd simply replace the word "ViewState" with "Session" in your masterpage. ViewState memory is specific to a single page (i.e. it is lost/cleared when the users navigates to a different page of your site) whereas session memory lasts for as long as your website is open in the browser. In addition, if you store your variables in the session, then you only need to get & store them once -- if you used the ViewState, you'd have to get & store them again on every page. –  Mar 18 '11 at 11:08
  • As a footnote, to see exactly what is causing an error in your code just place a breakpoint at the top of your page (or on any line that you want to interrogate) and hit F5 in Visual Studio. This allows you to step through and execute your page one line at a time -- this is called debugging. You'll do it a lot! –  Mar 18 '11 at 11:09
0

ViewState is per-page. When you navigate to the new page, it isn't set.

Your master page should put these into Session instead.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • But the error is occurring on the default page when I try and navigate away from it? – Matt Mar 18 '11 at 02:45
  • @Matt: so, what's your point? And are you certain that the error is _on_ the default page? How did you try to navigate away from it? In any case, it doesn't matter: ViewState is a property of an instance of a page. You should use `Session` state. – John Saunders Mar 18 '11 at 02:52
  • I have a Master page, which on its Load, sets the ViewState variabls.. The Default.aspx is the first page to be displayed, and the PreRender method grabs the variabls and displays them.. This all works fine.. If I have a link that navigates to another page, bob.aspx for example, then when I click the link, I get the error, which is on line 23 of the Default.aspx page.. Line 23 is lbl_FullName.Text = Master.CurrentFullName; – Matt Mar 18 '11 at 03:06
  • Oh and ViewState is the method MSDN is telling me to use – Matt Mar 18 '11 at 03:08
  • @Matt: MSDN is not telling you this. You are misunderstanding. If you change your code to use "Session" in the exact same way you are using "ViewState", then it will work. – John Saunders Mar 18 '11 at 03:11
  • I just changed ViewState to Session, but now my Default page doesn't show anything.. If I stick a button there that sets a label when clicked, then bam, everything shows up.. I want it to be displayed when it loads though – Matt Mar 18 '11 at 03:15
  • @Matt: first of all, use http://msdn.microsoft.com/en-us/library/wtxbf3hh.aspx instead. Second, exactly how are you "navigating away" from the page? Third, did any code ever _set_ `Master.CurrentUserName`? If it's not set, then that `ViewState` entry will always be null, and it will fail when it tries to cast to string. – John Saunders Mar 18 '11 at 03:22
  • Check my original post for the Page_Load statement for the Site.Master.cs file. I am navigating away using a link that exists on the Site.Master page on the left hand side.. its a simple hyperlink.. – Matt Mar 18 '11 at 03:32