Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 219
rusty Avatar asked Sep 14 '25 23:09

rusty


1 Answers

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.

like image 161
Oded Avatar answered Sep 16 '25 13:09

Oded