Search code examples
asp.netcode-behindascx

Is it possible to create two (or more) ASCX files with only one code behind file?


My current situation:

I have a user control A.ascx with code behind A.ascx.cs and B.ascx with code behind B.ascx.cs. Both code behind files contain similar code. Now I want to create only one CS file e.g. C.cs which can be used by A.ascx and B.ascx.

Of course, C.cs must be able to access controls by ID which were used inside A.ascx and B.ascx.

Is this possible?


Solution

  • No, but you can create single class and use it from both code behing classes. You can pass user control to that class and access controls by ID.

    Any if you wont typed access to controls do something like this :

    common class and interface that defines child controls that are on both user controls, and here you can access child controls :

      /// <summary>
      /// common controls
      /// </summary>
      public interface ICommonUserControl
      {
        TextBox TextBox1 { get; }
        Label Label1 { get; }
      }
    
      public class CommonCode
      {
        private ICommonUserControl commonUC;
        public CommonCode(ICommonUserControl uc)
        {
          this.commonUC = uc;
        }
    
        public void CommonWork()
        {
          this.commonUC.TextBox1.Text = "SomeText";
          this.commonUC.Label1.Text = "Other Text";
        }
      }
    

    and then on all User controls you must implement the ICommonUserControl interface, something like this :

      public partial class UC1 : System.Web.UI.UserControl, ICommonUserControl
      {
        public TextBox TextBox1 { get { return this.Uc1TextBox1; } }
        public Label Label1 { get { return this.Uc1Label1; } }
    
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
      }
    

    And at the end here is the example of usage :

      Control uc1 = this.LoadControl("UC1.ascx");
      this.phParent1.Controls.Add(uc1);
      Control uc2 = this.LoadControl("UC2.ascx");
      this.phParent2.Controls.Add(uc2);
    
      CommonCode cc1 = new CommonCode(uc1 as ICommonUserControl);
      cc1.CommonWork();
      CommonCode cc2 = new CommonCode(uc2 as ICommonUserControl);
      cc2.CommonWork();