1
votes

I am trying to set the text of two labels to random numbers on page load. This code

    Random random = new Random();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LINE 22 Label12.Text = random.Next(99).ToString();
            LINE 23 Label13.Text = random.Next(999).ToString();
        }

        foreach (string s in scr1.Style.Keys)
        {
            Response.Write(s + ",");
        }
    }
    ...

works on localhost but when run on my server throws a NullReferenceException.

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.] .apps..Page_Load(Object sender, EventArgs e) in C:\Users**\Documents\Visual Studio 2010\Projects****\apps**.aspx.cs:22 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35 System.Web.UI.Control.OnLoad(EventArgs e) +91 System.Web.UI.Control.LoadRecursive() +74 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207

1
Have you confirmed you've uploaded all the relevant changed files to the server?Andrew Morton
You're initiating your Random as a global variable (As seen in your description). Remember to make it Private Random random.TheGeekZn

1 Answers

3
votes

Two options:

  • Label12 could be null
  • random could have been set to null by some other piece of code

The first part of diagnosing the problem would be to work out which of those is the case. Simply split the assignment:

string randomText = random.Next(99).ToString();
Label12.Text = randomText;

Then see which line it fails on. Once you know which expression is null, you can try to work out why it's null.