Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 160
  • Last Modified:

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

0
Mike Eghtebas
Asked:
Mike Eghtebas
  • 4
  • 3
  • 2
  • +2
1 Solution
 
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
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

 
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
 
Mike EghtebasDatabase and Application DeveloperAuthor Commented:
That is great, thank you very much.

Mike
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 3
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now