Develop SharePoint 2010 Web Parts using Visual Studio 2010

Introduction

Web Parts is built on top of ASP.NET architecture and hence inherits some its key features. It is one of the core building blocks of SharePoint on which developers build and deploy these artifacts. Visual Studio 2010 introduced Visual Web Part template as one of its new features to deploy on the SharePoint Server. Here we will create a sample Web Part, ready for deployment in SharePoint Server. Before that lets assume you have following software installed.

System Requirements

1. Visual Studio 2010

2. SharePoint erver2010

3. Windows Server 2008

Steps to Follow

1. Open Visual Studio 2010

2. New Project

3. Navigate to the Installed Templates SharePoint section. This shows the list of available templates.

Visual Studio 2010 - New Project
Visual Studio 2010 - New Project

4. We shall select the Visual Web Part template.

5. Let's name our project MyWebPartProject

After the project is created, expand your project in Solution Explorer to view a number of default files created. Take note that the default name of the visual Web Part is VisualWebPart1. You may change the name by right clicking on it in Solution Explorer and selecting the rename option.

6. Now, right click on the ProductInfoCtrl.ascx file in Solution Explorer and select View in Designer.

7. Drag and drop controls from the toolbox onto the Web Part designer surface. The designer has three views: Design, Split and Code

8. Create a design

The code excerpt of the above UI is as follows.

Source code of WebPartUserCtrlt.aspx

<body>
    <style type="text/css">
        .style1
        {
            font-family: Verdana;
            font-size: medium;
            font-weight: bold;
        }
        .style2
        {
            font-family: Verdana;
            font-size: small;
            font-weight: bold;
        }
    </style>
    <p class="style1">
        Product Catalog</p>
    <p class="style2">
        Product:&nbsp;&nbsp;
        <asp:DropDownList ID="drpDwnProd" runat="server" Height="20px" 
			Style="margin-left: 21px" Width="200px">
            <asp:ListItem>Keyboard</asp:ListItem>
            <asp:ListItem>Mouse</asp:ListItem>
            <asp:ListItem>Processor</asp:ListItem>
            <asp:ListItem>Mothernoard</asp:ListItem>
            <asp:ListItem>Laptop</asp:ListItem>
        </asp:DropDownList>
    </p>
    <p class="style2">
        Description:
        <asp:TextBox ID="txtDesc" runat="server" Width="200px" 
			Enabled="False"></asp:TextBox>
    </p>
    <p class="style2">
        PROD:
        <asp:TextBox ID="txtPROD" runat="server" 
			Style="margin-left: 48px" Width="200px"
            Enabled="False"></asp:TextBox>
    </p>
    <p class="style2">
        Price:<asp:TextBox ID="txtPrice" runat="server" 
			Style="margin-left: 48px" Width="200px"
            Enabled="False"></asp:TextBox>
    </p>
    <p class="style2">
        Qty:
        <asp:TextBox ID="txtQty" runat="server" Width="200px" 
			Enabled="False"></asp:TextBox>
    </p>
    <p class="style1">
        <asp:Button ID="btnCalculate" runat="server" 
			OnClick="btnCalculate_Click" Text="Calc." />
    </p>
</body>

On our drag and drop of controls, Visual Studio adds CSS syntax styling to the UI automatically.

9. Now we need to add event handlers for the button. Double click on the button; this opens the code window and adds an onClick event to the button control design. Insert the following code.

Source Code of ProdInfoCtrl.ascx.cs ascx

using System;
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.Data;
namespace SampleWebPartProject.ProductInfo
{
    public partial class ProductInfoUserControl : UserControl
    {
        double tax = .11;
        double totalCost = 0.0;
        List<Products> listProduct = new List<Products>();
        protected void Page_Load(object sender, EventArgs e)
        {
            createProductList();
        }
        private void createProductList()
        {
            listProduct.Add(new Products()
            {
                strName = "Keyboard",
                strDesc = "USB Keynoard",
                strPROD =
                    "LJGHD9875",
                dblPrice = 23.00,
                intQty = 33
            });
            listProduct.Add(new Products()
            {
                strName = "Mouse",
                strDesc = "PS/2 Mouse",
                strPROD =
                    "JSHDHBK9385",
                dblPrice = 12.00,
                intQty = 22
            });
            listProduct.Add(new Products()
            {
                strName = "Processor",
                strDesc = "intel E7500.",
                strPROD = "LKJD4654LH",
                dblPrice = 456.99,
                intQty = 35
            });
            listProduct.Add(new Products()
            {
                strName = "Motherboard",
                strDesc = "intel DG31PR.",
                strPROD = "KSHDGH4565HG",
                dblPrice = 563.00,
                intQty = 27
            });
            listProduct.Add(new Products()
            {
                strName = "Laptop",
                strDesc = "Dell Core2Duo 2GB 500HDD",
                strPROD = "KJHASKJ566JH",
                dblPrice = 1234.99,
                intQty = 44
            });
        }
        protected void btnCalculate_Click(object sender, EventArgs e)
        {
            double dblCost = 0;
            string strPrice = "";
            switch (drpDwnProd.SelectedValue)
            {
                case "Keyboard":
                    dblCost = listProduct[0].dblPrice;
                    totalCost = dblCost + (dblCost * tax);
                    System.Math.Round(totalCost, 2);
                    strPrice = "$" + totalCost.ToString();
                    txtDesc.Text = listProduct[0].strDesc.
                    ToString();
                    txtPROD.Text = listProduct[0].strPROD.ToString();
                    txtPrice.Text = strPrice;
                    txtQty.Text = listProduct[0].intQty.
                    ToString();
                    break;
                case "Mouse":
                    dblCost = listProduct[1].dblPrice;
                    totalCost = dblCost + (dblCost * tax);
                    System.Math.Round(totalCost, 2);
                    strPrice = "$" + totalCost.ToString();
                    txtDesc.Text = listProduct[1].strDesc.
                    ToString();
                    txtPROD.Text = listProduct[1].strPROD.ToString();
                    txtPrice.Text = strPrice;
                    txtQty.Text = listProduct[1].intQty.
                    ToString();
                    break;
                case "Processor":
                    dblCost = listProduct[2].dblPrice;
                    totalCost = dblCost + (dblCost * tax);
                    System.Math.Round(totalCost, 2);
                    strPrice = "$" + totalCost.ToString();
                    txtDesc.Text = listProduct[2].strDesc.
                    ToString();
                    txtPROD.Text = listProduct[2].strPROD.ToString();
                    txtPrice.Text = strPrice;
                    txtQty.Text = listProduct[2].intQty.
                    ToString();
                    break;
                case "Motherboard":
                    dblCost = listProduct[3].dblPrice;
                    totalCost = dblCost + (dblCost * tax);
                    System.Math.Round(totalCost, 2);
                    strPrice = "$" + totalCost.ToString();
                    txtDesc.Text = listProduct[3].strDesc.
                    ToString();
                    txtPROD.Text = listProduct[3].strPROD.ToString();
                    txtPrice.Text = strPrice;
                    txtQty.Text = listProduct[3].intQty.
                    ToString();
                    break;
                case "Laptop":
                    dblCost = listProduct[4].dblPrice;
                    totalCost = dblCost + (dblCost * tax);
                    System.Math.Round(totalCost, 2);
                    strPrice = "$" + totalCost.ToString();
                    txtDesc.Text = listProduct[4].strDesc.
                    ToString();
                    txtPROD.Text = listProduct[4].strPROD.ToString();
                    txtPrice.Text = strPrice;
                    txtQty.Text = listProduct[4].intQty.
                    ToString();
                    break;
            }
 
        }
    }
}

Source Code for Product.csascx

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace MyWebPartProject.ProductInfo
{
    public class ProductInfo : WebPart
    {
        private const string _ascxPath =\
		   @"~/CONTROLTEMPLATES/MyWebPartProject/Product/@ProductInfoCtrl.ascx";
        
        protected override void CreateChildCtrls()
        {
            Control ctrl = this.Page.LoadControl(_ascxPath);
            Controls.Add(ctrl);
            base.CreateChildControls();
        }
        protected override void Render(HtmlTextWriter w)
        {
            base.RenderContents(w);
        }
    }
}

Product.webpart XML File

<?xml version="1.0" encoding="utf-8"?>
<webParts>
  <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    <metaData>
      <type name="MyWebPartProject.Product.Product,
		MyWebPartProject, Version=1.0.0.0, Culture=neutral,
		PublicKeyToken=db3art314308c42a" />
      <importErrorMessage>
        $Resources:core,ImportErrorMessage;
      </importErrorMessage>
    </metaData>
    <data>
      <properties>
        <property name="title" type="string">
          Product Information for the Web Part
        </property>
        <property name="Desc" type="string">
          Information about Computer and its accessories.
        </property>
      </properties>
    </data>
  </webPart>
</webParts>

10. Now this Web Part can be deployed in SharePoint Server.

A. Deploying the Visual Web Part Project

i. Right-click on the project in the Solution Explorer and select Build option. Make sure the solution builds.

ii. After that right-click the project in Solution Explorer again and select Deploy.

11. Once the project is successfully deployed, open your SharePoint site and create a new Web Part page and provide the information related to the particular Web Part page like û name and layout for the page.

12. Click Create. SharePoint creates the Web Part page.

13. Now to include Visual Web Part we have created and deployed in the server, we need to navigate to the Web Part page, click Site Actions the Edit Page. Choose Web Part Zone where we want to place our Web Part, click on Insert tab and then click on the Web Part on the Insert tab.

After this is done SharePoint shows a number of Web Part categories, to select a particular one to add to the Web Part zone. Navigate to Custom Category to see the recently created and deployed Web Part. Click the Product Web Part and then click on Add button. The Web Part is now included on the Web Part zone on the Web Part page.

Conclusion

Deploying and developing SharePoint Web Parts was not so easy prior to Visual Studio 2010. VS 2010 not only provides native tools and templates, but also excellent features to engage developers to tread in the path of SharePoint development. This article is terse; many in depth discussions were intentionally omitted. Readers who are interested may explore others; there are quite a number of features included with the up grade of this version of Visual Studio.

TAGS:

development, SharePoint 2010, Visual Studio 2010, Web Parts
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Networking Solutions

Most Popular SharePoint Stories

Partners

More Networking