Wednesday, March 9, 2011

ListViewByQuery control with custom code in SharePoint 2010

Renders a list view within a Web Part or ASPX page according to a specified query.

Namespace: Microsoft.SharePoint.WebControls
.aspx code or web part control code:

<SharePoint:ListViewByQuery ID="myListQuery" runat="server"/>

.cs file code:

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);

You can also check SharePoint 2010 Articles.