Reputation: 499
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?
Upvotes: 4
Views: 13462
Reputation: 498992
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.
Upvotes: 5