Visit our SharePoint Forum

SharePoint developer? Submit Yourself as Freelancer

Sunday, February 3, 2008

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);
}


}
}



5 comments:

Janardan Baghla said...

thanks for useful information.hey..can u post how to deploy webpart as feature in sharepoint..i need this in detail..i tried all those links but i cudn't get it...

Anonymous said...

Nice !!!!!!!!

Create Custom SharePoint WebParts, it is simple.
Try this too,
Custom SharePoint WebParts

Anonymous said...

im getting Object reference not set to an instance of an object. : The file /layouts/WebUserControl.ascx does not exist. error please help
i followed the steps u said above.

Anonymous said...

im getting Object reference not set to an instance of an object. : The file /controls/WebUserControl.ascx does not exist. error please help
i followed the steps u said above.

Anonymous said...

I am getting Could not load type usercontrol.ascx error what can i do?

SharePoint Programming