We help IT Professionals succeed at work.

NullReferenceException, c#

190 Views
Last Modified: 2014-08-11
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

Comment
Watch Question

Kyle AbrahamsSenior .Net Developer
CERTIFIED EXPERT

Commented:
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 EghtebasDatabase and Application Developer

Author

Commented:
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 AbrahamsSenior .Net Developer
CERTIFIED EXPERT

Commented:
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

CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
Which line raises the exception? The one you highlighted in your code snippet should not have.
Mike EghtebasDatabase and Application Developer

Author

Commented:
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
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
Ah. Never mind, then. I missed that you were using the DropDownList in that line. I s'pose Kyle has you sorted out  = )

Commented:
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 DavisDir Internet Svcs

Commented:
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 EghtebasDatabase and Application Developer

Author

Commented:
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/Programming/Languages/C_Sharp/Q_28493754.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
Senior .Net Developer
CERTIFIED EXPERT
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Mike EghtebasDatabase and Application Developer

Author

Commented:
That is great, thank you very much.

Mike

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.