Designing custom webparts - the easy way#

Controls
Custom webparts are basically Custom Controls, which means they have Render method in which the output is rendered. The Sharepoint Webpart pack template for Visual Studio 2003 implements this in a RenderWebPart Method.

protected override void RenderWebPart(HtmlTextWriter output)
{
}

You'll have to do it with this method. So creating control will be sometihng like control myControl = new control which will be rendered like myControl.RenderControl(output). For 1 or 2 buttons and some HMTL, this will do just fine.

However, when developing complex (in design) custom webparts with lots of HTML, controls and its eventhandlers, the RenderWebPart method gets complex and hard to deal with. Standard, there is no design mode with custom webparts.

Design
A solution for this problem is to create a control that can be designed easily and render it in your webpart. Which controls? UserControls!

  1. First, create a virtual directory in your Sharepoint Web
  2. Exclude this path in the central administration of your virtual server (define managed paths).
  3. Create a Web Application Project in this virtual directory. Design a UserControl (with postback and all) and build it.
  4. Now add a custom webpart project in Visual Studio and add the UserControl project as a reference.
  5. Build the solution and put the dll in the Sharepoint bin directory (or GAC, or change the debug output path to the bin directory so the dll is build in the sharepoint site automatically)
  6. Register the webpart as safe (in your web.config) and insert it on your Sharepoint page. (you might want to do a IISRESET)
  7. In the webpart CS file, insert this code:

protected UserControl MyControl;
protected override void CreateChildControls()
{
   MyControl = (UserControl)base.Page.LoadControl(“[relative path to usercontrol]“);
   // i.e. /UserControls/UCTest.ascx
   // add control to base
   base.Controls.Add(MyControl);
   base.CreateChildControls();
}

protected override void RenderWebPart(HtmlTextWriter output)
{
   // render control
   MyControl.RenderControl(output);
}

Now, build the solution and refresh the page. The UserControl will be displayed including its eventhandlers. It's that easy!

Thursday, December 16, 2004 7:42:28 AM UTC #     | 

 

All content © 2012, Mart Muller
On this page
This site
Calendar
<February 2012>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910
Archives
Sitemap
Disclaimer

Powered by: newtelligence dasBlog 1.9.7174.0

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Send mail to the author(s) E-mail

Theme design by Jelle Druyts