views:

42

answers:

2

Hello, 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?

+1  A: 

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);
Justin Niessner
Can you explain why this works? I made a similar commen myself (apparently 6 minutes after this answer so I'll go delete it now) but I couldn't work out why doing this would work whereas what the original poster did doesn't work. I assume that what is being returned by LoadControl *is* an Editor and if its put in a control first it should be possible to then put it in a user control. Assuming of course that Editor does definitely implement UserControl...
Chris
A: 

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;
Guffa