Link to home
Start Free TrialLog in
Avatar of Mike Eghtebas
Mike EghtebasFlag 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

Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

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.
Avatar of 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
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

Which line raises the exception? The one you highlighted in your code snippet should not have.
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
Ah. Never mind, then. I missed that you were using the DropDownList in that line. I s'pose Kyle has you sorted out  = )
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
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
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
ASKER CERTIFIED SOLUTION
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That is great, thank you very much.

Mike