Top Menu

Wednesday, June 4, 2014

SharePoint 2013 - Web Part Development

In this post, I am going to demonstrate how to develop a SharePoint 2013 Web Part and then deploy it on local SharePoint site. For production deployment see this post.
Lets get started!
  1. Launch Visual Studio 2013 with Administrator privileges.
  2. Select SharePoint Solutions -> SharePoint 2013 - Visual Web Part and provide name of the project along with the location.
  3. Provide the url of local SharePoint site for debugging then select Deploy as a sandboxed solution option and hit finish.
  4. You will see the basic structure of the Visual web part created along with one User Control (ASCX) to handle GUI elements and one Feature to handle packaging (WSP).
  5. Open the user control (VisualWebPart1.ascx) and add following ASP.NET Grid.
    <asp:GridView ID="gvProducts" runat="server" />
    
  6. Open the code behind of the user control (VisualWebPart1.ascx.cs) and add the following code:

    Add Reference to SharePoint API
    using Microsoft.SharePoint;
     Add CreateChildControls() function
    protected override void CreateChildControls()
    {
        SPSite objSite = SPContext.Current.Site;
        using (SPWeb objWeb = objSite.OpenWeb())
        {
            SPQuery objQuery = new SPQuery();
            objQuery.ViewFields = "<FieldRef Name='ID' /><FieldRef Name='Title' /><FieldRef Name='Author' />";
            objQuery.ViewFieldsOnly = true;
    
            SPList objList = objWeb.Lists["ListA"];
            SPListItemCollection oCollection = objList.GetItems(objQuery);
    
            gvProducts.DataSource = oCollection.GetDataTable();
            gvProducts.DataBind();
    
        }
    }
    Your code should look like this:
  7. Select Build -> Deploy Solution.
  8. Open IE and go to the site specified in the step 3. Edit the home page and select Insert -> Web Part. You should see this web part under Custom category, select and add the webpart.
  9. It should display like this
For Packaging and deployment check out the next post.

No comments:

Post a Comment

Official SharePoint Documentation

I have recently contributed to the official SharePoint documentation for developement. Check it out here: https://docs.microsoft.com/en-us...