Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
 
 
DZone MVB

Links

Social

SharePoint: SPList.HasView() extension method

One quick posting. I wrote yesterday extension method for SharePoint that checks if view exists. I think it is far better for performance if I don’t live on try…catch to find out if view exists or not. Extension method that you have to put in static class is here.

C#
/// <summary>
/// Determines whether the specified list has view with given name.
/// </summary>
/// <param name="list">The list to search from.</param>
/// <param name="viewName">Name of the view.</param>
/// <returns>
///     <c>true</c> if the specified list has view; otherwise, 
///     <c>false</c>.
/// </returns>
[CLSCompliant(false)]
public static bool HasView(this SPList list, string viewName)
{
    if(string.IsNullOrEmpty(viewName))
        return false;
 
    foreach(SPView view in list.Views)
        if(view.Title.ToLowerInvariant() == 
           viewName.ToLowerInvariant())
            return true;
 
    return false;
}

VB.NET


''' <summary>
''' Determines whether the specified list has view with given name.
''' </summary>
''' <param name="list">The list to search from.</param>
''' <param name="viewName">Name of the view.</param>
''' <returns>
'''     <c>true</c> if the specified list has view; otherwise,
'''     <c>false</c>.

''' </returns>
<CLSCompliant(False)> _
<System.Runtime.CompilerServices.Extension> _
Public Shared Function HasView(ByVal list As SPList, _
   
ByVal viewName As String) As Boolean
 
    If String.IsNullOrEmpty(viewName) Then
        Return False
    End If
    
    For Each view As SPView In list.Views
        If view.Title.ToLowerInvariant() = _
          
viewName.ToLowerInvariant() Then
            Return True
        End If
    Next
    
    Return False
End Function

Posted: May 12 2009, 07:21 PM by DigiMortal | with 2 comment(s)
Filed under:

Comments

Links (5/14/2009) « Steve Pietrek – Everything SharePoint and Office said:

Pingback from  Links (5/14/2009) &laquo; Steve Pietrek &#8211; Everything SharePoint and Office

# May 14, 2009 8:57 PM

dood said:

Good.

But i think the performance would be bad when you have 1000+ views. try catch ftw!

# June 11, 2010 10:32 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)