Cannot implicitly convert type 'System.Web.UI.Control' to 'System.Web.UI.UserControl

5.6k Views Asked by At

am trying to load usercontrol in c#.

Can add the .ascx onto my .aspx page by using the code below:

    Control MyUserControl;
    MyUserControl = LoadControl("~/controls/Editor.ascx");
    PlaceHolder1.Controls.Add(MyUserControl);

However, I want to pass ID into Editor.ascx, top of the Editor.ascx contains the following code:

private int m_id = 0;
public int ID
{
    get { return m_id; }
    set { m_id = value; }
}
protected void Page_Load(object sender, EventArgs e)    
{
    if (!Page.IsPostBack && !Page.IsCallback)
    {
        using (DataClassesDataContext db = new DataClassesDataContext())
        {
            TB_Editor.Text = db.DT_Control_Editors.Single(x => x.PageControlID == ID).Text.Trim();
        }
    }

}

I tried casting control to user control so I can get access to ID see below

UserControl Edit = (UserControl)MyUserControl;

But I get a cast error.

any ideas?

2

There are 2 best solutions below

1
On

I think your problem is your casting when you load the control. You should cast to the most specific type (in this case, Editor), pass the parameters you need, and then add the control to the placeholder.

Try this:

Editor myUserControl = (Editor) LoadControl("~/controls/Editor.ascx");
myUserControl.ID = 42;
PlaceHolder1.Controls.Add(myUserControl);
0
On

You get that error when you have a reference of type Control and try to assign to a UserControl variable without casting:

UserControl myUserControl;
myUserControl = LoadControl("~/controls/Editor.ascx");

The LoadControl method returns a Control reference even if the actual type of the object inherits UserControl. To assign it to a UserControl variable you need to cast it:

UserControl myUserControl;
myUserControl = (UserControl)LoadControl("~/controls/Editor.ascx");

However, the UserControl class doesn't have the ID property that you want to access. To get access to that you need a reference of the specific type of your user control. For example:

MyEditorControl myUserControl;
myUserControl = (MyEditorControl)LoadControl("~/controls/Editor.ascx");
myUserControl.ID = 42

Or you can just create the specific reference on the fly to set the property:

Control myUserControl;
myUserControl = LoadControl("~/controls/Editor.ascx");
((MyEditorControl)myUserControl).ID = 42;