'NullReferenceException in usercontrol from class library, but not from web project

I have following project structure where web application may contain user controls from the same web project or from a separate class library. The issue is in Default.aspx.cs, when I execute usercontrol2.SetValues(); I receive NullReferenceException since for some reason textbox2 is null. I've tried using EnsureChildControls(); but it does not help either. Should I register or invoke these usercontrols in some other way? Why does not it work out-of-box?

solution usercontrol 1 usercontrol 2

User control in web project

WebUserControl1.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.WebUserControl1" %>

<asp:TextBox runat="server" ID="textbox1"></asp:TextBox>

WebUserControl1.ascx.cs

namespace WebApplication1
{
    public partial class WebUserControl1 : System.Web.UI.UserControl
    {
        public void SetValues()
        {
            textbox1.Text = "Hello";
        }
    }
}

User control in class library

WebUserControl2.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl2.ascx.cs" Inherits="ClassLibrary1.WebUserControl2" %>

<asp:TextBox runat="server" ID="textbox2"></asp:TextBox>

WebUserControl2.ascx.cs

namespace ClassLibrary1
{
    public partial class WebUserControl2 : System.Web.UI.UserControl
    {
        public void SetValues()
        {
            textbox2.Text = "world";
        }
    }
}

Main page

Default.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<%@ Register tagPrefix="web" tagName="WebUserControl1" src="WebUserControl1.ascx" %>
<%@ Register TagPrefix="web" Namespace="ClassLibrary1" Assembly="ClassLibrary1" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <web:WebUserControl1 runat="server" ID="usercontrol1"></web:WebUserControl1>
    <web:WebUserControl2 runat="server" ID="usercontrol2"></web:WebUserControl2>
</asp:Content>

Default.aspx.cs

using System;
using System.Web.UI;

namespace WebApplication1
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            usercontrol1.SetValues(); // OK
            usercontrol2.SetValues(); // NullReferenceException
        }
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source