Monday, March 30, 2009

Using ListView by Query in webpart

Scenario:
I wanted to display information into grid using a CAML query

Solution:
Share Point has a ListViewByQuery Control which can help.

Code:

using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace Training
{
public class myWebPart: System.Web.UI.WebControls.WebParts.WebPart
{
public override void RenderControl(HtmlTextWriter writer)
{
ListViewByQuery view = new ListViewByQuery();

SPWeb currentweb = SPContext.Current.Web;
SPList list = currentweb.Lists["Shared Documents"];
view.List = list;
SPQuery query = new SPQuery(view.List.DefaultView);
query.ViewFields = "<FieldRef Name='Title'/>";
query.Query = "<Where><Contains><FieldRef Name='Subject'/><Value Type='Text'>Sample</Value></Contains></Where>";
view.Query = query;
EnsureChildControls();
view.RenderControl(writer);
RenderChildren(writer);
}
}
}
Article:

7 comments:

Julian,  October 12, 2011 at 10:05 AM  

Hi, your post was really useful!!! But the problem I'm having right now is that I want to filter by the ID asigned by sharepoint to the list item. But the query is not working and it brings me all the items.

Sandeep October 12, 2011 at 10:52 AM  

So 2 things

1. Make sure 'ID' is ViewFields list
2. Query should have a filter on it

Julian,  October 12, 2011 at 12:44 PM  

Thanks for your quick reply...I'm actually doing that but it not bring the selected item.

Julian,  October 12, 2011 at 12:53 PM  

I forgot to specified that I tried the query in the CAML Builder and it works perfects but when I implement this as a spquery, it doesn't work. Do may know why??

Sandeep October 12, 2011 at 7:12 PM  

I will check on my own my vm today and let U know

Sandeep October 12, 2011 at 8:01 PM  

Works for me
here's what i tried

1. created new doc library
2. uploaded 5 documents
3. web part has this code


public override void RenderControl (HtmlTextWriter writer)
{
ListViewByQuery view = new ListViewByQuery();

SPWeb currentweb = SPContext.Current.Web;
SPList list = currentweb.Lists["Shared Documents"];
view.List = list;
SPQuery query = new SPQuery(view.List.DefaultView);
query.ViewFields = "";
query.Query = "2";
view.Query = query;
EnsureChildControls();
view.RenderControl(writer);
RenderChildren(writer);
}

Srujan,  March 26, 2012 at 4:51 PM  

Hi ,

Is there way to display column Totals (i.e. aggregatoins) in ListViewByQuery

Regards
Srujan.N