SParc
SParc

Reputation: 1779

NullReferenceException on setting label text of a custom user web control

I am trying to set a custom user web control's label text as

Email em = new Email(); //Email is the class of the custom user web control
em.setEmail(email);
Panel2.Controls.Add(em);

The setEmail() function in the control sets the value of the label lblEmail as

public void setEmail(string recEmail)
{
        lblEmail.Text = recEmail;
}

But I am getting following error: enter image description here

When debugging I saw that recEmail is getting the value as provided. But not assigning it to the lblEmail.Text.

I thought it might be due to control registration problem, so I registered it as

<%@ Register Src="~/Email.ascx" tagname="Email" TagPrefix="uc1" %>

I also tried setting the value in the setEmail() function like this:

public void setEmail(string recEmail)
{
        string a=recEmail;
        lblEmail.Text = a;
}

When debugging this showed that a is getting the value of recEmail but its not assigning to the lblEmail.Text

As I can't upload the whole code, so please note following points:

  1. The panel named Panel2 is in an UpdatePanel that updates conditionally after email control is added to the panel.
  2. The Email.ascx file is in the parent folder of the file that is calling it. Means if Email.ascx is in A folder then the file calling it is in A/B folder. But I don't think so that's going to effect. Just mentioned to give you the complete information about the situation.

Please tell me what to do to solve this?

Upvotes: 1

Views: 1627

Answers (1)

David
David

Reputation: 219057

By default, members of the user control are null until they are initialized. And initialization doesn't happen in the constructor for user controls (and pages, and probably some other similar types). They happen when the control is "loaded" into a context of some sort.

Instead of initializing like this:

Email em = new Email();

Take a look at the LoadControl() method. You should instead initialize it like this:

Email em = (Email)LoadControl("Email.ascx");

This will initialize the user control by firing its built-in page life-cycle events, where its UI controls are initialized.

Upvotes: 3

Related Questions