Home > Sharepoint 2007 > Create SPView programmatically with Group by Option

Create SPView programmatically with Group by Option

You can create a view ( SPView ) with group by option. SPViewCollection add method takes couple of parameters. Most important to explain is View Fields and Query. Both are string variables. in View fields, you can mention  the fields that you want to display in the view. Query contains your where clause, group by clause and order by clause. Query is CAML syntax. Please note order by is rows order while the Columns order is your view fields. It means you should add fields names in order that you want.
        SPList plList=oWeb.Lists["MyList"];

          // create new default view that is grouped
            string viewQuery = @"
                <GroupBy Collapse=""FALSE"" GroupLimit=""100"">
                  <FieldRef Name=""Year"" Ascending=""FALSE"" />
                  <FieldRef Name=""Year"" Ascending=""FALSE"" />
                  <FieldRef Name=""Period"" Ascending=""FALSE"" />
            StringCollection viewFields = new StringCollection();
            plList.Views.Add("Grouped By Year", viewFields, viewQuery, 100, true, true, SPViewCollection.SPViewType.Html, false);

Categories: Sharepoint 2007
  1. Sid
    April 6, 2011 at 8:06 am

    I am trying to add a new view using the fields of an existing one.
    But, the new view returns no items. However, if I modify the new view and just click OK/Cancel (without making any changes to the View settings), the items get populated. Any suggestions or ideas?

    • Nand
      August 9, 2011 at 7:55 am

      May Be view is not getting updated view.update() as well as list.update() needs to be done

  2. utsab
    May 8, 2013 at 2:56 pm

    just what i was looking for.


  3. February 25, 2015 at 10:47 am

    It was useful, Thanks!

  4. VonZ
    May 12, 2015 at 2:42 pm

    Great Thanks! How do I add the option to “Show all items without folders” in my view?

  5. May 13, 2015 at 11:00 am

    You will need to set two parameters to false after 100 below in Views.Add line of code like

    plList.Views.Add(“Grouped By Year”, viewFields, viewQuery, 100, false, false, SPViewCollection.SPViewType.Html, false);

  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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: