Thursday, March 11, 2010

Webpart containing usercontrol in MOSS 2007

Step 1. Create a web application.

Step 2. Create a UserControl in this web application.

Step 3. Add another Project (sharepoint webpart) to this solution.

Step 4. Add the following code to the .cs file of the webpart. This is the minimal code to load a usercontrol in a webpart.


Control controlObject;
String userControlURI = @"~/UserControls/YourUserControl.ascx";
public FCWebPart()
{
}

protected override void CreateChildControls()
{
base.CreateChildControls();

try
{
controlObject = this.Page.LoadControl(userControlURI);
if (controlObject != null)
{
controlObject.ID = "UCID";
Controls.Add(controlObject);
}
}
catch { }
}

protected override void Render(HtmlTextWriter writer)
{
try
{
controlObject.RenderControl(writer);
}
catch (Exception e)
{
writer.Write(e.Message);
}
}

Step 5. Create a folder named UserControls in the virtual directory (the folder of the site).

Step 6. Place the .ascx file of the usercontrol in this folder.

Step 7. Open the .ascx file in notepad and delete the followong code "CodeBehind="YourUserControl.ascx.cs"

Step 8. Build the solution and copy the dll of the web application.

Step 9. Put the dll in the bin directory of virtual directory.

Step 10. Right click on the webpart project and see the properties. Here put the link of the sharepoint site in Debug box.

Step 11. Now Right click on the webpart project and click Deploy.

No comments: