Friday, March 8, 2013

create view to List programaticallly

[Code]

private void CreateView(SPWeb oWeb)
        {          
            SPSecurity.RunWithElevatedPrivileges(delegate()            {                string strViewName = "myView";                bool bAlreadyExists;              
                SPList oList = oWeb.Lists["Pages"];                SPViewCollection oViewCollection = oList.Views;
                var newWeb = GetRootWeb(oWeb);
               addContentTypeToList(oList);
                StringCollection viewFields = AddFieldsToView();
                bAlreadyExists = CheckViewExist(oViewCollection);
                if (bAlreadyExists) return;                                   oViewCollection.Add(strViewName, viewFields, Query, 10, true, false);                oWeb.Update();            });        }
        private string Query        {            get            {                string query;                query = string.Format(@" <Where>                                        <Eq>                                            <FieldRef Name='ContentType' />                                            <Value Type='Computed'>{0}</Value>                                        </Eq>                                    </Where>                               <OrderBy>                                 <FieldRef Name='Created' Ascending='FALSE' />                       </OrderBy>", mycontentType);
                return query;            }        }
        private static StringCollection AddFieldsToView()        {            StringCollection viewFields= new System.Collections.Specialized.StringCollection();
            try            {                viewFields.Add("field1");                viewFields.Add("field2");                viewFields.Add("field3");                viewFields.Add("field4");            }            catch (Exception e)            {                //write code when exception happen            }            return viewFields;        }

   private static SPWeb GetRootWeb(SPWeb oWeb)        {            SPWeb newWeb = oWeb;            while (!newWeb.IsRootWeb)            {                newWeb = newWeb.ParentWeb;            }            return newWeb;        }

  private void addContentTypeToList(SPList oList)        {            if (oList.ContentTypes[myCTName] == null)            {                oList.ContentTypes.Add(myCT);                oList.Update();            }        }
        private static bool CheckViewExist(SPViewCollection oViewCollection)        {            bool bAlreadyExists=false;
            foreach (SPView vItem in oViewCollection)            {                if (vItem.Title == "myView")                {                    bAlreadyExists = true;                    break;                }
            }            return bAlreadyExists;        }

No comments:

Post a Comment