Web Parts the Simple Way - Use User Controls

One of the first questions I usually get about SharePoint development is how to make the WebPart development process simpler. My answer to that is use UserControls. There is a very good solution on CodePlex called Smart Parts https://www.codeplex.com/smartpart However I have found in some environments the customer does not want to add a third party product into the mix. In these cases the fastest way I have found to create webparts is to use user controls and wrap them with the webpart.

 

We start with a very simple WebPart class that only overrides the CreateChildControls method, we use this to load our user control.

 

public class InboxListWebPart: WebPart

{

    private Control control = null;

    protected override void CreateChildControls()

    {

        Controls.Clear();

        control = this.Page.LoadControl("/_controltemplates/MyCustomControls/InboxListControl.ascx");

        Controls.Add(control);

    }

}

From there everything is driven from my usercontrol InboxListControl.ascx. The control goes into the program files\common files\microsoft shared\web server extensions\12\templates\controltemplates directory (as shown above I created a sub directory called MyCustomControls). I usually will deploy the code behind into the GAC, but they can be deployed into the same directory as well.

If you need to do more advanced webpart stuff (like connections or properties) you can get to your webpart from your user control. For example if I had a property that I wanted to present to the user (say like Inbox Name) in my .cs file for the webpart I would do the following (using the 3.5 property syntax):

[Personalizable(PersonalizationScope.User), WebBrowsable(true), WebDisplayName("Inbox Name"), WebDescription("some useful description")]

public string InboxName

{

    get;

    set;

}

In my user control I usually define a parent webpart property that returns the webpart I used to wrap my user control:

private InboxListWebPart ParentWebPart

{

    get

    {

        return this.Parent as InboxListWebPart;

    }

}

From here I can now define my InboxName on my user control:

public String InboxName

{

    get

    {

        return ParentWebPart.InboxName;

    }

    set

    {

        ParentWebPart.InboxName = value;

    }

}

It takes a little more code when you want to do things like properties and connections, but I think the usability of having your UI in an ascx file more then makes up for this small inconvenience.