Creating a Web Part For SharePoint – Standard vs Visual Web Parts

A common SharePoint developer task is to create a custom Web part. SharePoint 2010 include two different Web Parts –  Standard and Visual. A standard Web part provides the core infrastructure which allows you to create and deploy Web parts to SharePoint. In contrast a Visual Web Part fully utilizes the designer surface in Visual Studio to allow for features such as drag and drop as well as double clicking controls to wire up events.
Firstly looking at Standard Web Parts, since SharePoint is built on top of ASP.NET, you can apply common ASP.NET coding techniques.  The below code snippet shows  a Label , Textbox, and Button control that are being instantiated and properties set, as well as a Click event that corresponds to the Button control:

namespace MyFirstDevTask.FistTaskWebPart
{
[ToolboxItemAttribute(false)]
public class FistTaskWebPart: WebPart
{
Label label1= new Label();
TextBox textbox1 = new TextBox();
Label responseLbl= new Label();
Button button1= new Button();
protected override void CreateChildControls()
{
Label1.Text = “Enter Text:”;
responseLbl.Text = ““;
textbox1 .Enabled = true;
textbox1 .Text = ““;
myButton.Text = “Click Me”;
this.Controls.Add(Label1);
this.Controls.Add(textbox1 );
this.Controls.Add(new LiteralControl(“
”));
this.Controls.Add(responseLbl);
this.Controls.Add(new LiteralControl(“
”));
this.Controls.Add(button1);
button1.Click += new EventHandler(button1_Click);
}
void button1_Click(object sender, EventArgs e)
{
string userResponse = Label1.Text;
responseLbl.Text = userResponse;
}
}
}

In the above snippet,  the four controls are declared at the class level. Then, in the CreateChildControls method, the properties for those objects are set. The Add method is called to add the controls to the Controls collection (to display them in the Web part), and the myButton_Click event is called to render the user’s entry as text in one of the labels.

If you have not coded Web parts before, this is pretty standard — that is, creating the controls, setting the properties for those controls, adding the controls to the Controls collection, and then adding any event handlers for those controls.

Continues…

Pages: 1 2




Array

No comments yet... Be the first to leave a reply!