Today, I was trying to display list data in a Web Part programmatically and have it behave the same way as the default SharePoint lists do. I was given a Web Part that was using an SPGridView to do this, but the filtering in it didn't work the way it was supposed to and it also didn't show which column it was filtered on (as default SharePoint lists do).
Thanks to this post, I was able to render the list the same way default lists get rendered. Here's an example on how to do it for the tasks list, including an example Caml query that sorts the view by title and filters it so that it shows only the incomplete tasks assigned to the current user. Beware though: when using this Caml query, sorting and filtering won't work since it will always render the view by the conditions you have provided in your query. Still working on solving this...
private string html;
protected override void OnPreRender(EventArgs e)
using (SPSite mySite = SPContext.Current.Site)
using (SPWeb myWeb = mySite.OpenWeb())
SPList myList = myWeb.Lists["Tasks"];
SPView myView = myList.Views["All Tasks"];
SPQuery myQuery = new SPQuery(myView);
myQuery.Query = "<OrderBy><FieldRef Name=\"Title\" /></OrderBy><Where><And><Eq><FieldRef Name=\"AssignedTo\" /><Value Type=\"User\"><UserID/></Value></Eq><Neq><FieldRef Name=\"Status\" /><Value Type=\"Choice\">Completed</Value></Neq></And></Where>";
html = myList.RenderAsHtml(myQuery);
this.Title = "Tasks";
protected override void Render(HtmlTextWriter writer)