Pages

Monday 15 July 2013

Creating SharePoint List Views using C#

Hi All,
Sometimes OOB views are not enough and you may go for a custom views.
I have explained here. how can you create a custom list view.

1. Create a feature and give it a good  name.





















2. Add event reciever to this feature





















A Feature has many events.
i) Feature Activated
ii) Feature Deactivating
iii) Feature Installed
iv) Feature Uninstalling
v) Feature Upgrading

3. So  , go in code file of event reciever and uncomment the Feature Activated method
and write code for you view here.
Example:

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
                SPSite osite = null;
                SPWeb oweb = null;
               // DateTime currentyear = DateTime .Now.Year
                try
                {
                   osite = SPContext.Current.Site;
                    oweb = SPContext.Current.Web;
                    using (SPSite site = new SPSite(osite.ID))
                    {
                        using (SPWeb thisWeb = site.OpenWeb(oweb.ID))
                        {
                            SPList oList = thisWeb.Lists["Report List"];
                            SPViewCollection oViewCollection = oList.Views;
                            string strViewName = "Test View";   // you view name here...
                            System.Collections.Specialized.StringCollection viewFields =
                            new System.Collections.Specialized.StringCollection();
                            viewFields.Add("FieldName1");
                            viewFields.Add("FieldName2");
                            viewFields.Add("FieldName3");
                            viewFields.Add("FieldName4");
                            viewFields.Add("FieldName5");
                            viewFields.Add("FieldName6");
                            viewFields.Add("FieldName7");
                            viewFields.Add("FieldName8");
                            viewFields.Add("FieldName9");

                          string query = "<Where><And><Geq><FieldRef Name='FieldName1'/><Value IncludeTimeValue='TRUE' Type='DateTime'>" + dtmonday + "</Value></Geq><Leq><FieldRef Name='FieldName1'/><Value IncludeTimeValue='TRUE' Type='DateTime'>" + dtfriday + "</Value></Leq></And></Where>";
                            oViewCollection.Add(strViewName, viewFields, query, 1000, true, false);

                            thisWeb.Update();
                        }
                    }
                }
            catch(Exception ex)
              {
            
            }
        }


4. After that deploy the solution the target site.
5. Go in site settings-->sitecollection features (features are both at site and web level. its on you what you chosse at feature creation time.)
6. Activate the feature.(if not activated)
Your custom view is ready now.

No comments:

Post a Comment