1
Panel pnl_Confirmation = (Panel)form1.FindControl("ConfirmationPanel") as Panel;
    pnl_Confirmation.Visible = false;

I keep getting a "NullReferenceException" in the above code. "ConfirmationPanel" is a panel I show/hide depending on if the form is submitted successfully or not.

The panel is wrapped in a LoginView control, which is why I cannot call "ConfirmationPanel" directly:

<asp:LoginView ID="LoginView1" runat="server">
<LoggedInTemplate> 
<asp:Panel id="ConfirmationPanel" runat="server" Wrap="False">

...

Why is this null? It should be referencing the Panel with the ID "ConfirmationPanel", no?

Thanks

4
  • 2
    Panel pnl_Confirmation = (Panel)form1.FindControl("ConfirmationPanel") as Panel; Why are you casting twice? Commented Nov 19, 2010 at 21:18
  • 1
    This may not be the sort of comment you want, but is there any way you can work with MVC instead? ASP.NET webforms is concentrated evil. Commented Nov 19, 2010 at 21:19
  • 1
    You don't need both types of type casts: "as Panel" is sufficient. Commented Nov 19, 2010 at 21:20
  • is the panel visible for the first time when you execute the statement Panel pnl_Confirmation = (Panel)form1.FindControl("ConfirmationPanel") as Panel; ? Commented Nov 19, 2010 at 21:20

5 Answers 5

4

Try this:

Panel pnl_Confirmation = LoginView1.FindControl("ConfirmationPanel") as Panel;
if(pnl_Confirmation != null)
   pnl_Confirmation.Visible = false;
Sign up to request clarification or add additional context in comments.

1 Comment

This worked. Thanks! It seems I was casting twice, as well as referencing from "form1" instead of "LoginView1".
2

It all depends where you have that code. If you have it before Page_Load(), the control tree is probably not built yet, hence the null reference.

Comments

1

Use the FindControl of LoginView instead

Panel pnl_Confirmation = LoginView1.FindControl("ConfirmationPanel") as Panel;

Because it's part of the LoginView template.

Comments

1

"FindControl will find a control only if the control is directly contained by the specified container; that is, the method does not search throughout a hierarchy of controls within controls. " (from the MSDN documentation)

i.e. call FindControl on LoginView or create a recursive FindControl

Comments

0

It seems you try to typecast twice.

Try to only typecast once with either works best:

Panel pnl_Confirmation = (Panel)form1.FindControl("ConfirmationPanel");

or

Panel pnl_Confirmation = form1.FindControl("ConfirmationPanel") as Panel;

It is also important to verify whether your reference is not null before trying to access it

if (pnl_Confirmation != null)
    pnl_Confirmation.Visible = false;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.