Webpart Development part 3: Adding controls to web part
by Hojo Clement • March 25, 2010 • MOSS 2007 • 2 Comments
In Part 2 of this article, we discussed how to deploy Web part .
In this article we will se how to add controls in web part.
1. Create a new web part project (refer part1)
2. Override the method CreateChildControls
protected override void CreateChildControls()
{
base.CreateChildControls();
TextBox txtName = new TextBox();
this.Controls.Add(txtName);
Button btnSubmit = new Button();
btnSubmit.Text = "Submit Name";
this.Controls.Add(btnSubmit);
}
3. Buid your project and pakage it. So that you can deploy in your site and use it.
Next we will see how to bind a user control in a SharePoint web part
1. Create web user control
2. Open web part project
3. Override the method CreateChildControls
protected override void CreateChildControls()
{
base.CreateChildControls();
UserControl usercontrol = (UserControl)Page.LoadControl("/_layouts/ BlogPostListing.ascx");
this.Controls.Add(usercontrol);
}
4. Build the project and package it.
Note: Before deploying web part in server you have to copy user control (.ascx and .ascx.cs) in layouts folder. This blog post will help you learn how to pack the user controls and web part in a single WSP.
There are many advantages in using user control instead of writing code directly in web part. Some of them are
- Usercontrol is easy to develop
- Easy to debug
- Compile and Deploy time overhead reduced. If you want to modify anything in web part then all you have to do is just modify the aspx page or the .CS file. No need to deploy the dll in GAC or bin and above all there is no need for an IIS RESET.
In the coming articles we will see how to add custom properties to web part.

Pingback: Webpart Development part 2: Deployment
Pingback: Webpart Development part 4: Creating Custom Web Part Properties