Brian Roisentul
Brian Roisentul

Reputation: 4750

How to display the User Control within a webpart, in SharePoint

I'm building a webpart for SharePoint 2010, but I've already created a repeater and a couple of methods executed on the Load method of the webpart's user control.

Now, I want to include that control in the webpart, so I can see it in SharePoint, because I actually don't see it, although I'm adding it to the webpart as follows, in the CreateChildControls method:

        VisualWebPart1UserControl uc = new VisualWebPart1UserControl();

        this.Controls.Add(uc);

What am I missing?

Upvotes: 1

Views: 4829

Answers (1)

Kyle Trauberman
Kyle Trauberman

Reputation: 25694

What you are doing is essentially manually creating a visual webpart.

The visual webpart template uses the following code to acheive this result:

public class VisualWebPart1 : WebPart {
    // Visual Studio might automatically update this path when you change the Visual Web Part project item.
    private const string _ascxPath = @"~/_CONTROLTEMPLATES/VisualWebPart1/VisualWebPart1UserControl.ascx";

    protected override void CreateChildControls() {
        Control control = Page.LoadControl(_ascxPath);
        Controls.Add(control);
    }
}

You might want to consider just creating a visual webpart in Visual Studio and replacing the .ascx file with your control.

Upvotes: 1

Related Questions