Sunday, December 27, 2009

Converting Web User Control to Web Part in Sharepoint 2007


Many of web part have complex design, of-course we can create this web part by using code-behind code. In other words, creating the controls dynamically, Take a look at this sample web part:

Protected Overloads Overrides Sub CreateChildControls()
MyBase.CreateChildControls()

Dim btnShowMessage As New Button()
btnShowMessage.Text = "show Message"

AddHandler btnShowMessage.Click, AddressOf btnShowMessage_Click
Me.Controls.Add(btnShowMessage)
End Sub

Private Sub btnShowMessage_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim lbl1 As New Label()
lbl1.Text = "Hello Guest"

Me.Controls.Add(lbl1)
End Sub


so if we want to create complex web part (I mean web part contains many controls) this way will take a lot of time and efforts, so I found another way to create a simple or complex web part, after researching, anyway here are the steps:

1) Create your Web User Control. You have the option on how you create it, but in my part, I create it using ASP.NET 2.0 IDE. What I usually did is I create a blank page, then I add a new item which is Web User Control. Take note to uncheck the option which separate your code in a separate file.

2) Design your Web User Control (ascx), from its physical design to its logic coding.
3) compile the solution
4) drag and drop the solution DLL in \windows\assembly 
5) browse the DLL inside the assembly folder the right click and select properties
6) Copy the Public Key Token its look like e3dc1ba93544f2e9
7) open ascx file and insert the following line at the end of Inherits property.
  , NameSpace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e3dc1ba93544f2e9

8) now after pasting the code the new page register tage will be like this
<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="MyUserControl.ascx.vb"
    Inherits="MyTestSolution.MyUserControl, MyTestSolution, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e3dc1ba93544f2e9" %>




3) Copy the modified ascx file to this directory:

         c:\inetpub\wwwroot\wss\VirtualDirectories\2222\wpresources

   Where: 2222: the number of port that your site using
               wpresources: you can use any other folder.

4) Write the following code for adding your web user control file in your .vb file:

Protected Overrides Sub CreateChildControls()

MyBase.CreateChildControls()
dim objUserControl as Control
objUserControl= Page.LoadControl("~/wpresources/MyUserControl.ascx")
Me.Controls.Add(objUserControl)
End Sub


With Speacial Thanks to Mr. Moutasem Al-awa for his assistance

2 comments: