Tuesday, December 8, 2009

Create SharePoint List View Programmatically


In this post I’m going to describe how you can programmatically add a view to SharePoint list or Document Library. You can get this work done by using SPViewCollection.Add Method (Microsoft.SharePoint), here is a sample code,
        public void createListView()
        {
            SPSite site = new SPSite("http://merdev-moss:5050/testsara");
            SPWeb web = site.OpenWeb();
            SPList list = web.Lists["Tasks"];

            SPViewCollection allviews = list.Views;
            string viewName = "Test View";

            System.Collections.Specialized.StringCollection viewFields = new System.Collections.Specialized.StringCollection();
            viewFields.Add("Title");
            viewFields.Add("Priority");

            string myquery = "<Where><Gt><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Gt></Where>";
            allviews.Add(viewName, viewFields, myquery, 100, true, false);
        }
Above code creates a view in the collection with the specified name "Test View" and added view fields. Query string will return all items, because always ID is greater than 0. Row limit is 100 and the view displays items page by page. Last Boolean mean it is not the default view.

Please refer my article on CAML & SPQuery in SharePoint to find out easy way to write CAML quires used in above code.

Add View Using Existing View

You also can create new List View with the help of existing one, this sample code will create new View which has another field using above created View.
        public void _createListView()
        {
            SPSite site = new SPSite("http://merdev-moss:5050/testsara");
            SPWeb web = site.OpenWeb();
            SPList list = web.Lists["Tasks"];

            SPViewCollection allviews = list.Views;
            string viewName = "New Test View";

            System.Collections.Specialized.StringCollection viewFields = list.Views["Test View"].ViewFields.ToStringCollection();
            viewFields.Add("Status");

            string myquery = "<Where><Gt><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Gt></Where>";
            allviews.Add(viewName, viewFields, myquery, 100, true, false);
        }

0 comments:

Post a Comment

Was this information helpful?
Your comments always encourage me to write more, you can post your comment here.

Related Posts :

Related Posts with Thumbnails