Wednesday, December 3, 2008

SharePoint's ListViewWebPart

To use SharePoint's ListViewWebPart directly in your ASPX page, follow these steps:

1) Register Microsoft.SharePoint.WebPartPages namespace in ASPX page :



<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages"
Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>




2) Add following ListViewWebPart's html code :


<WebPartPages:ListViewWebPart ID="oListViewWP" runat="server" __WebPartId="{GUID}"
WebPart="true"></WebPartPages:ListViewWebPart>


Note :
Replace GUID in above code either by a newly generated GUID or if you are using SharePoint designer, then SharePoint designer will automatically insert a new GUID in your HTML code when you try to save the ASPX page.


3) Add following server side code to populate data in ListViewWebPart :


SPWeb oWebsite = SPContext.Current.Web;
SPList oList = oWebsite.Lists["Announcements"];

oListViewWP.ListName = oList.ID.ToString("B").ToUpper();
oListViewWP.ViewGuid = oList.Views["MyView"].ID.ToString("B").ToUpper();

oListViewWP.GetDesignTimeHtml();


Note :
Don't forget to write oListViewWP.GetDesignTimeHtml();, otherwise ListViewWebPart will not display any data in it.

Here MyView is just a dummy SPView name, you can use either default SPView or can create a new SPView with only desired columns and settings.

====================================================================
====================================================================

Now if you want to hide/remove the ToolBar from ListViewWebPart, then as per me following are the two ways :
1) Set SuppressWebPartChrome property of WebPart


oListViewWP.SuppressWebPartChrome = true;



2) One of the problem with above code is that it hide the toolBar in ListViewWebPart as well as in the SPList/SPView from which it is displaying the data
( I face this problem, not sure about others :) ).

So, the other alternative is to add following CSS in our code:


<style type="text/css">
.ms-menutoolbar { display: none; }
</style>


Be careful while using the above CSS, because it hide all the ToolBars which uses the .ms-menutoolbar CSS class.


Reference :
MSDN Forum


====================================================================
====================================================================

If you want to apply Filter on ListViewWebPart's column or in other words, display data in ListViewWebPart with only desired column value, then write following code :


string columnValue = "SP";
oListViewWP.FilterString = "FilterField1=Title&FilterValue1=" + columnValue;



The above code results in the display only those records whose column name Title has value SP.

====================================================================
====================================================================

Another major challenge that i faced while using ListView WebPart (or in any normal WebPart) is to change/modify the Empty message or no record message.

The exact message is : There are no items to show in this view of the "ViewName" list. To create a new item, click "New" above.

One of the way to change this message is to modify the ViewEmpty XML node of ListViewXml.

Following code snippet describes the way to change the empty message of ListView WebPart :


//oListViewWP is ListView WebPart instance
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(oListViewWP.ListViewXml);
XmlNode node = xmlDoc.SelectSingleNode("//ViewEmpty");
if (node != null)
{
StringBuilder strB = new StringBuilder();
strB.Append("<HTML><![CDATA[<SPAN Class='ms-vb' style='width:200px;'>]]></HTML>");
strB.Append("<HTML>There is no item to show.</HTML>");
strB.Append("<HTML><![CDATA[</SPAN>]]></HTML>");

node.InnerText = strB.ToString();
}

oListViewWP.ListViewXml = xmlDoc.OuterXml;
oListViewWP.GetDesignTimeHtml();



Note : It is required to set the ListViewXml before GetDesignTimeHtml() function call.


Otherwise, if you are using SharePoint Designer and using/populating ListView WebPart in design time. Then simply search following text :
There are no items to show in this view of the and replace it with your required/desired message.


Another way is to change/modify the text directly in core.resx file that reside at following location :
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\Resources\core.resx.

Note : If we change the core.resx file, it will be gets reflected in all sites that are using the core.resx resource file.

19 comments:

Anonymous said...

Hi Avinash,

1) Is there a way to set the __webpartId mentioned in step 2 to be set through code?
2) Also when trying to use olistViewWebPart.GetDesigntimeHtml(), it throws "Null Reference error". what must be going wrong ?

Avinash said...

Hi Laxmikant,

1) I am not sure, but you can try oListViewWP.WebId to set the WebPart ID (GUID).

2) Regarding Null reference --- I think you need to instantiate the ListViewWebPart control. I created the control in html (Step 2).

~ Avinash

Unknown said...

Gents - a very basic question here - where would the server code be plugged into?

A script tag or can this is in the aspx.cs - thanx!

Anita said...

Hi Harsh,

Its upto your requirement, you can placed server-code either in same aspx page (using script tag) or in sepearate code-behind file (*.cs / *.vb).


Refer following post: How to write Server-side ( C# ) code in SharePoint custom pages.


~ Avinash

Unknown said...

I cannot emphasize how much i need to thank you.
I am new to moss and was unable to create a listviewwebpart programmatically.
I did as indicated at a blog but was getting error that the list dos not exists or is deleted.
I finally found on your blog that i hadnt set the listname property of the Listviewwebpart. Surprisingly couldnt find the solution even after searching on google for long..till now.

Thanks a lot :-)

Avinash said...

Hi Sohail,

Always welcome :)
I am really glad... that my blog helps you....

Wue said...

Better way to hide Toolbar is:
XmlDocument ListViewXML = new XmlDocument();
ListViewXML.LoadXml(ListViewWP.ListViewXml);
XmlNode ToolBar = ListViewXML.SelectSingleNode("View/Toolbar");
if (ToolBar != null)
{
ToolBar.Attributes["Type"].Value = "none";
}
ListViewWP.ListViewXml = ListViewXML.OuterXml;

Taranath Chebrolu said...

Hi Avinash,

I am able to render the litviewwebpart dynamically based on my input as list name. The issue is - the folder of the share point list in the listview webpart not allowing to navigate. I mean ot say it is not allowing to see the sub folders/files wht it contains. do u have any idea how to resolve this issue.

Regards
Taranath

Ruud said...

Good post, thanks! A easier way to hide the toolbar can be achieved by adding the line
lsvwp = new ListViewWebPart();
lsvwp.Controls[0].Visible = false;

Unknown said...

Hi Avinash,
I instantiated a new SPView oject and bind it to the ListViewWP. If there are items for the view, the WP displays it. No issues. However if there are no items, the default error message is shown. Tried setting the ViewEmpty attribute of the view to a custom message. When I deploy the custom message is seen, but the header row is missing. Is this the normal behaviour?

Using the olistViewWP.GetDesigntimeHeader() makes no difference and olistViewWebPart.GetDesigntimeHtml(), throws "Null Reference error". If I dont use olistViewWebPart.GetDesigntimeHtml, it works fine.

Please suggest what needs to be done if I need to show the header when the view has no items to display and also have the custom empty view message.

Cheers
Vijay

Avinash said...

Hi Vijay....

Check this link..
http://social.msdn.microsoft.com/Forums/en-US/sharepointcustomization/thread/fc3d96d1-b991-40b7-9bf7-f7b3bb3bd5fc/

Shang - Xu said...

Hi Avinash

Great post!

Would you please advise how to add a command (checkbox or button) column to the LVWP, so that when the checkbox is checked, I could run some server site code? (e.g. I want to move the item to another document library)

Awaiting online.

Thank you so much!

Avinash said...

Hi Shang,

I am not sure about LVWP, but you can use SPGridView to achieve same.

Refer this post...
http://sharepoint.coultress.com/2008/06/adding-checkbox-to-spgridview-in.html

Unknown said...

Hi,
I have used your code but when the webpartListView displays it shows a error message "This list don't exist". I have verified that de list is correct.
Any ideas?

Thanks!

Surya Pulipati said...

Hi,

when i try to exectute this code, here iam getting error

node.SelectSingleNode("Toolbar")

as it is returning null value.

how can i fix this ?

Thanks,
Surya

Surya Pulipati said...

hi,
i am getting in the below line code

node.SelectSingleNode("Toolbar")

Plz let me know how to fix this.

Thanks,
Surya

Anonymous said...

Hi Avinash,

Your code worked like a charm and I was also able to modify empty message as well.
Thanks for the great post, though I have an issue and am not able to figure out.

I have this custom web part on a page and configured to show a view from Document Library. Now I have put another OOTB list web part of the same document library by going through add webpart and selecting that document library. Now when I refresh the page some of the columns from custom webpart are missing except Name, Modified and Modified By, however the OOTB webaprt is working fine. I have debug the code and figured out that after binding data with ListViewWP.GetDesignTimeHtml() and observing string output, the missing columns are absent.

Any help will be greatly appreciated.

Thanks

Avinash said...

Hi,

Personally I faced this issue, that whenever I placed two or more ListView Webpart (WP) (or similar WP like DataView WP), the WP behaved unexpectedly.

The only conclusion that I was able to made was that...as these WP work based on the SPList's GUID (and/or SPView's GUID) passed as QueryString...so it get confused.

So as per me...use only one ListView WP per page.

Anonymous said...

Really very helpful post.
Here I am filtering data according to "Created By". It works fine on page render but facing an issue that when I click on Sorting/Filter option.. it gives all the values exist .
How can put filter on this values also.
I am using XsltListViewWebPart tag instead of ListViewWebPart tag. Because I am getting an error of Not compatible type error in it.

Google