0
votes

I have an textbox inside an user control. I created dinamically this user control and load in placeholder.

But when I tried to assign a value to the textbox, I raised next below error:

Object reference not set to an instance of an object

This is the user control:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="IVT_FormClient.ascx.cs" Inherits="Evi.Sc.Web.Evi.IVT.Sublayouts.IVT_FormClient" %>
<asp:Panel ID="pnlContainer" runat="server">        
    <asp:TextBox ID="txtClientNumber" runat="server"></asp:TextBox>
</asp:Panel>

The access modifier is (In the user control):

public string TxtFirstName
{
    get { return txtFirstName.Text; }
    set { txtFirstName.Text = value; }
}

In the web form I have the control reference:

<%@ Reference Control="~/Evi/IVT/Sublayouts/IVT_FormClient.ascx"   %>

In the code behind of the user control is:

    public partial class frm_VerifyIdentity : System.Web.UI.Page
    {
        IVT_FormClient ivtFormClient = new IVT_FormClient();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
            IVT_FormClient ivtFormClient = (IVT_FormClient)LoadControl("~/Evi/IVT/Sublayouts/IVT_FormClient.ascx");

                Client UserClient = new Client();

                UserClient = Load_ClientVerification(Server.HtmlEncode(Request.QueryString["ID"]).Trim());

                if (UserClient != null)
                {
                    ivtFormClient.TxtFirstName = UserClient.FirstName;
                    plhFormClient.Controls.Add(ivtFormClient);
                }

            }
        }
 }

The error occur is this line of code:

                ivtFormClient.TxtFirstName = UserClient.FirstName;
1

1 Answers

0
votes

Do not create an instance of a UserControl via constructor but with LoadControl as you have already done in Page_Load. However, you are doing that only if(!IsPostBack). Hence the control is instantiated the next postback via constructor.

Also, you have to recreate dynamic controls on every postback. I would suggest to add the UserControl delaratively to the page. You can hide/show it accordingly. Otherwise you need to create/add it always, best in Page_Init instead of Page_Load.

So this is not best-practise(just add it to the page) but should work as desired:

IVT_FormClient ivtFormClient = null;

protected void Page_Init(object sender, EventArgs e)
{
    ivtFormClient =(IVT_FormClient)LoadControl("~/Evi/IVT/Sublayouts/IVT_FormClient.ascx");
    Client UserClient = new Client();
    UserClient = Load_ClientVerification(Server.HtmlEncode(Request.QueryString["ID"]).Trim());

    if (UserClient != null)
    {
        ivtFormClient.TxtFirstName = UserClient.FirstName;
        plhFormClient.Controls.Add(ivtFormClient);
    }
}