Wednesday, February 23, 2011

List.DefaultView is null ?

I bet many of you fall for this one… I know I did.

You got a SPList object, you want to get the default view, or the default view name, so you write:

list.DefaultView.Title

You never even bother to check if DefaultView is null or not, right? Because it doesnt make sense…

Well, I had a customer who did something crazy.

He created a redirection page inside a list forms folder, and marked it as the default view for the list using SharePoint Designer 2007.

* You will be glad to hear that in SharePoint Designer 2010 this is not possible anymore :)

Well, from this point on, calling the list.DefaultView object returns null, which made our code fail since we didn’t think of checking if there is a valid default view for the list.

So, a lesson to be learned: never trust anyone in SharePoint!

A quick fix I did for it is to see if list.DefaultView is null, and if so, to loop through all list views and get the first valid view.

Here is the code I used:

internal static SPView GetSafeListDefaultView(SPList list, string hideViews)
{
if (list.DefaultView != null)
return list.DefaultView;
else
{
foreach (SPView view in list.Views)
{
if (
view.Hidden ||
string.IsNullOrEmpty(view.Title.Trim()) ||
//Explorer View or subject view in discussion - allow subject views.
(view.BaseViewID == "3" && view.ContentTypeId.ToString() == "0x") ||
(hideViews.IndexOf(";" + view.Title.ToLower() + ";") >= 0) ||
//reply views in discussion board
(list.BaseTemplate == SPListTemplateType.DiscussionBoard && !view.ContentTypeId.ToString().StartsWith("0x012001"))
)
continue;

return view;
}
}

throw new Exception("Could not get a safe default view for this list: " + list.Title);
}

So from now on,  I will use this method to get the list default view, and never again trust the list.DefaultView property, which may be null.


By the way, the proper way to do what the customer wanted is to change the list.RootFolder.WelcomePage to the redirection page he created. Changing the default view is not the best idea, and I am not sure if it is supported.


Cheers, Shai.

No comments: