This is one of those cases where I went down several dead ends and spent way too much time chasing after all kinds of reasonable, yet ineffective, approaches, only to collapse in a heap, look up, and see the solution, glimmering above me, all shiny and simple.
The problem at hand: Now that I've got a hold of a SharePoint list (SPList) object, and I also have the View I want to use to display this list (SPView), what are my options for rendering?
Stated more clearly: I have a particular View that is configured on the site that I want to use to drive which items, columns, and sort rules are used when I display my SPList. I want to do all this in a loosely-coupled way so that future changes to the site's view will be reflected in my rendered SPList.
Dead End #1: Bind the SPList to a GridView. This is surprisingly ugly, though it does reveal a lot of details about what's going on under the hood of the SPListItems. Try it some time just for fun. It's educational, but not what you want.
Dead End #2: Attempt to create some other object that I can then bind to a GridView. How about a DataTable? Simple enough: build a bunch of columns, then populate the rows. Tried this, would have worked, but the effort to do so was a lot more steep than I'd expected, and it seemed like it would be error prone to continue going that route.
The shiny, simple, hindsight-is-20-20 solution: ahem...
myListObject.RenderAsHTML(myQuery);
d'oh.
Ok, here's what I ended up doing (roughly, my actual code is sprinkled across several methods, much of the error handling is removed for clarity):
// SPSite = site collection
SPSite mySite = SPControl.GetContextSite(Context);
// You really need to set the following CatchAccessDeniedException = false setting!
// In the event the current logged in user does not have access to the Web
// (or any other resources) you are attempting to open later,
// this prevents SharePoint from automatically redirecting them to a
// "Authorization Required" page. Instead you will throw a catch-able exception
// which is not ideal as the answer to UserHasPermission() but it seems to be
// all we have.
mySite.CatchAccessDeniedException = false; // now we won't redirect on error
SPWeb myWeb = mySite.AllWebs["sitename"];
SPList myList = myWeb.GetList(SPEncode.UrlEncodeAsUrl("/Lists/MyListName"));
SPView myFavoriteView = myWeb.GetViewFromUrl(SPEncode.UrlEncodeAsUrl("/Lists/MyListName/MyFavView.aspx"));
SPQuery query = new SPQuery(myFavoriteView);
Literal litOutputGoesHere = new Literal();
litOutputGoesHere.Text = myList.RenderAsHtml(query); // easy!
Posted
05-31-2007 2:18 AM
by
Unclaimed Blog