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

LVL 34
Mike EghtebasDatabase and Application DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kyle AbrahamsSenior .Net DeveloperCommented:
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.
0
Mike EghtebasDatabase and Application DeveloperAuthor 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
0
Kyle AbrahamsSenior .Net DeveloperCommented:
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

0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

käµfm³d 👽Commented:
Which line raises the exception? The one you highlighted in your code snippet should not have.
0
Mike EghtebasDatabase and Application DeveloperAuthor 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
0
käµfm³d 👽Commented:
Ah. Never mind, then. I missed that you were using the DropDownList in that line. I s'pose Kyle has you sorted out  = )
0
dejaanbuCommented:
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
0
Gary DavisDir Internet SvcsCommented:
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
0
Mike EghtebasDatabase and Application DeveloperAuthor 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.

http://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
0
Kyle AbrahamsSenior .Net DeveloperCommented:
Your issue is not with the session variable.  Using the session variable  and the use of your session variable was fine in the code.

As I originally stated your issue was your referencing of the dropdownlist control which was null:


The simple fix for this is:

DropDownList ddl = (DropDownList)td.FindControl("cboRegion");

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

You will find that your text is not being set on the DDL.  That's because you're not finding the DDL properly.



There was a slight issue in option 1 that I provided:
c = RecursiveFind(ctrl, ID);          

I was missing the id to pass to the function in the recursive call.

Was there something else not working with it?
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Mike EghtebasDatabase and Application DeveloperAuthor Commented:
That is great, thank you very much.

Mike
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.