.Net - How to create UserControl that implements an interface? Error with LoadControl

12,577

This will work:

var myFirstTab = (IMyTabInterface)uControl1;
var mySecondTab = (IMyTabInterface)uControl2;

myFirstTab.LoadData();
mySecondTab.LoadData();

Panel1.Controls.Add((Control)myFirstTab);
Panel1.Controls.Add((Control)mySecondTab);

What is going on?

Your myFirstTab and mySecondTab variables are of type IMyTabInterface, since this is what you declared them as (this is what allows you to call LoadData on them).

However, in order to add an item to the controls collection, these need to be of type Control (or one that inherits from it) - this is achieved by the cast.


Another option:

var myFirstTab = (IMyTabInterface)uControl1;
var mySecondTab = (IMyTabInterface)uControl2;

myFirstTab.LoadData();
mySecondTab.LoadData();

Panel1.Controls.Add(uControl1);
Panel1.Controls.Add(uControl2);

Here you use the original Control types you started with, so no need to cast.

Share:
12,577
rusty
Author by

rusty

Updated on June 04, 2022

Comments

  • rusty
    rusty almost 2 years

    I have a number of UserControls that I want to each have some basic functionality. Below is my implementation :

    public interface IMyTabInterface
    {
        void LoadData();
    }
    
    public partial class MyFirstTab : System.Web.UI.UserControl, IMyTabInterface
    {
        public void LoadData()
        {
            ...
        }
    
    }
    

    Then, in another page's code behind, I try :

        protected void LoadFirstTab()
        {
            Control uControl1 = Page.LoadControl("/Controls/MyFirstTab.ascx");
            Control uControl2 = Page.LoadControl("/Controls/MySecondTab.ascx");
    
            // Want to do something like this, but don't get this far... :
            var myFirstTab = (IMyTabInterface)uControl1;
            var mySecondTab = (IMyTabInterface)uControl2;
    
            myFirstTab.LoadData();
            mySecondTab.LoadData();
    
            Panel1.Controls.Add(myFirstTab);
            Panel1.Controls.Add(mySecondTab);
        }
    

    I know much of this is not correct yet, but I am getting an error on the LoadControl() line :

    'MyFirstTab' is not allowed here because it does not extend class 'System.Web.UI.UserControl'

    even though the class clearly extends the UserControl class. Whats going on here? Is there a better way to do this?

  • rusty
    rusty over 13 years
    Hi Oded, Thank you for your reply. I totally made a bonehead mistake and this question should be deleted - I had changed the namespace on the control thats why the LoadControl() function was breaking. Doh! Only realized this after I scrapped all my interface code to start over only to still get the same errors. Woops.