Sunday, July 5, 2009

Create Web Part for Sharepoint With User Control

Brief:
To Create a Web Part for sharepoint sites, Create a User control in Visual studio(handling all the events). Drag it into a sharepoint Webpart application(project). And Finally, Deploy the webpart into sharepoint site.

Steps are:

1. Create a blank web application and add a web user control (name WebUserControl1.ascx) into it.

2. Add one TextField and a Button to the user control. The ids of these controls are TextBox1 and Button1 respectively.

3. Add a button1_click even in codebehind file of WebUserControl1 , i.e. WebUserControl1.cs
Like:
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = "I am in Web part -> In user control ";
}

3. Now copy this user control to a new folder,name it "controls".The folder should be placed under your (Web Application)
path.eg: “C:\Inetpub\wwwroot\wss\VirtualDirectories\80\controls\”.

4. Create a New Web part application using Visual Studio SharePoint Web Part template.

And The code in Web part application goes below:

using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace WepPart_Usercontrol
{
[Guid("68dd6b12-7b2d-4dc8-941f-80acbf83f16f")]

public class WepPart_Usercontrol : System.Web.UI.WebControls.WebParts.WebPart
{

UserControl userControl;

public WepPart_Usercontrol()
{
this.ExportMode = WebPartExportMode.All;
}

protected override void Render(HtmlTextWriter writer)
{
userControl.RenderControl(writer);
}
protected override void CreateChildControls()
{

base.CreateChildControls();
userControl = (UserControl)Page.LoadControl(@"/controls/WebUserControl1.ascx");
Controls.Add(userControl);
}


}
}

No comments:

Post a Comment