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 http://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.

publicclassInboxListWebPart: WebPart

{

privateControl control = null;

protectedoverridevoid 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):