Home > SharePoint > How to create Views Programmatically in SharePoint 2010

How to create Views Programmatically in SharePoint 2010


Below is the code snippet to create views programmatically

Create a View

      private void CreateView(string strViewName)
{
try
{
string fieldName = //Get Field Internal Name
var docquery = "<Where><Eq><FieldRef Name='" + fieldName.ToString() + "' /><Value Type='Choice'>" + strViewName.ToString() + "</Value></Eq></Where>";
System.Collections.Specialized.StringCollection viewFields = new System.Collections.Specialized.StringCollection();
viewFields.Add("Type");
viewFields.Add("Name");
viewFields.Add("Modified");
viewFields.Add("Modified By");
viewFields.Add(fieldName.ToString());
oViewCollection.Add(strViewName, viewFields, docquery, 100, true, false);
web.Update();
}
catch (Exception e)
{
throw new SPException(e.Message.ToString());
}
}

You can use U2U Query Builder tool to build CAML query (http://www.u2u.net/res/Tools/CamlQueryBuilder.aspx)

 

Advertisements
  1. Nici
    October 14, 2011 at 2:40 am

    Hi – Thanks for the post. Where do I deploy this so that sharepoint sees the new view I am trying to create?

    Thank you
    -Nici

    • October 14, 2011 at 6:00 pm

      You should deploy this as a feature. Once deployed, go to Site Features and activate it.

      You will then see the new view under the document library.

      Thanks

      Kanu

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: