Avatar of Mike Eghtebas
Mike Eghtebas
Flag for United States of America asked on

NullReferenceException, c#

Question, why do I get NullReferenceException error in this code?

How can I correct this.

Thank you.

 

        string r = (string)(" ");
        r = Session["Region"].ToString();     // stepping shows r = "Region 1"

      if (IsPostBack)
        {
            if (Session["Region"] != null)
            {
                MasterPage myMaster = Master as MasterPage;
                DropDownList regionDropDownList = (DropDownList)myMaster.FindControl("cboRegion");
                regionDropDownList.Text = Session["Region"].ToString();   //  <---  NullReferenceException  **********
            }
        }

Open in new window

C#ASP.NET.NET Programming

Avatar of undefined
Last Comment
Mike Eghtebas

8/22/2022 - Mon
Kyle Abrahams, PMP

You're not finding regionDropDownList.

To resolve the error:

if (regionDropDownList  != null)
 regionDropDownList.Text = Session["Region"].ToString();


To find the drop down correctly:
The find control isn't recursive.  
   You need to do the find control on cboRegion's parent or create a recursive find.
Mike Eghtebas

ASKER
re:> You're not finding regionDropDownList.

How do I find it? I know you are telling "You need to do the find control on cboRegion's parent or create a recursive find."

The parent of the control is myMaster (see line 10).

Is it possible to give me some lines of code I can work with?

Thank you,

Mike
Kyle Abrahams, PMP

here's a recursive find:

    private Control RecursiveFind(Control root, string id)
    {
        
        if (root.ID == id)
            return root;

        Control c = null;

        foreach (Control ctrl in root.Controls)
        {
            c = RecursiveFind(ctrl);            
            if (c != null) 
                 break;
        }

        return c;

    }

Open in new window


Instead of calling the findcontrol:
DropDownList regionDropDownList = (DropDownList) RecursiveFind(myMaster, "cboRegion");


the other way to do this:
assume your master has the following:

<body>
<asp:Panel runat="Server" id = "A">
   <asp:DropDownList runat="server" ID="B" />
</asp:Panel>

master.Controls Only returns "A"
You would have to find control your way down.
eg:
Panel p = (Panel)Master.FindControl("A");
DropDownList ddl = (DropDownList)p.FindControl("B");

Open in new window

This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
kaufmed

Which line raises the exception? The one you highlighted in your code snippet should not have.
Mike Eghtebas

ASKER
kaufmed,

Yes, at line 12 (regionDropDownList.Text = Session["Region"].ToString();   //  <---  NullReferenceException  **********).

--------------
Kyle Abrahams,

First solution I tried, was not successful. I will try it again making sure this time around I implement it correctly.

For the second solution, instead of a panel, I have table cell (<td ID="Region"> tag), I will try it using:
MasterPage myMaster = Master as MasterPage;
TableCell td = (TableCell)Master.FindControl("Region");
DropDownList ddl = (DropDownList)td.FindControl("cboRegion");
ddl.Text = Session["Region"].ToString();

Open in new window


Thanks to all,

Mike
kaufmed

Ah. Never mind, then. I missed that you were using the DropDownList in that line. I s'pose Kyle has you sorted out  = )
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
dejaanbu

If the control that you want to access is inside a ContentPlaceHolder control on the master page, you must first get a reference to the ContentPlaceHolder control, and then call its FindControl method to get a reference to the control.

http://msdn.microsoft.com/en-us/library/vstudio/c8y19k6h(v=vs.100).aspx
Gary Davis

Looking at your code...

      string r = (string)(" ");
      r = Session["Region"].ToString();     // stepping shows r = "Region 1"

      if (IsPostBack)
        {
            if (Session["Region"] != null)
              :
              :

Open in new window


Line 1 sets r to a space but line 2 replaces it with the session variable. You could combine these into one line since r does not need to be initialized as a space.

If the session variable does not exist, it will be null. Doing the .ToString() will then cause the null reference trap.

In line 6, you actually test the session variable for null which is correct but too late.

You could set r to the session variable using a cast insteat of using ToString(). That way r will be the string or null:

    string r = (string)Session["Region"];

Open in new window


Gary Davis
Mike Eghtebas

ASKER
Hi All,

Having lost my grounding with use of session variables for now, with apology, I have switched to solve the problem using Serialization/Deerialization.

https://www.experts-exchange.com/questions/28493754/using-Serialization-Deerialization-object-c.html

But, after I get a solution this way, I will come back later and learn more about session variables.

I appreciate for any comment on this new question if you have time for it.

Regards,

Mike
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
ASKER CERTIFIED SOLUTION
Kyle Abrahams, PMP

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Mike Eghtebas

ASKER
That is great, thank you very much.

Mike