Show list view web part in a visual web part in SharePoint

This SharePoint tutorial, we will discuss how to show list view web part in a custom visual web part in SharePoint.

Show List View web part in visual web part in SharePoint

First, we create a SharePoint visual web part using visual studio. Now we add the following code under webpart.cs file in CreateChildControls() method for showing the list view web part under the visual web part.

XsltListViewWebPart XLV = new XsltListViewWebPart();
SPWeb web1 = SPContext.Current.Web;
SPList lists = web1.Lists["Leave Details"]; //your list name
XLV.ListId = lists.ID;
XLV.ViewGuid = lists.DefaultView.ID.ToString(); //default view
this.Controls.Add(XLV);

Now your webpart.cs file looks like this. See the whole code

using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace LeaveApplication.LeaveWebPart
{
[ToolboxItemAttribute(false)]
public class LeaveWebPart : Microsoft.SharePoint.WebPartPages.WebPart
{
// Visual Studio might automatically update this path when you change the Visual Web Part project item.
private const string _ascxPath = @"~/_CONTROLTEMPLATES/LeaveApplication/LeaveWebPart/LeaveWebPartUserControl.ascx";
protected override void CreateChildControls()
{
LeaveWebPartUserControl control = Page.LoadControl(_ascxPath) as LeaveWebPartUserControl;
XsltListViewWebPart XLV = new XsltListViewWebPart();
SPWeb web1 = SPContext.Current.Web;
SPList lists = web1.Lists["Leave Details"];
XLV.ListId = lists.ID;
XLV.ViewGuid = lists.DefaultView.ID.ToString();
this.Controls.Add(XLV);
if (control != null)
{
control.lwebpart = this;
}
Controls.Add(control);
}
protected override void RenderContents(HtmlTextWriter writer)
{
base.RenderContents(writer);
}

Now save and deploy your web part. Now open your site in the browser where you deploy the web part.

Now add that web part in your page where you want to show. Now you see your list view web part under your custom web part. See in fig

Show List View web part in visual web part in SharePoint

You may like following SharePoint tutorials:

This is how we can show the list view web part in a visual web part in SharePoint.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>