Monday, 13 February 2012

Create list programmatically using console application


 public static void createlist()
        {
            try
            {
                using (SPSite osite = new SPSite("http://admin-pc:2345"))
                {
                    using (SPWeb oweb = osite.OpenWeb())
                    {
                        SPListTemplate template = oweb.ListTemplates["Custom List"];

                        if (oweb.Lists.TryGetList("Training list new") == null)
                        {
                            oweb.AllowUnsafeUpdates = true;
                            oweb.Lists.Add("Training list new", " ", template);
                            SPList olist = oweb.Lists.TryGetList("Training list new");
                            olist.Fields.Add("field1", SPFieldType.Text, false);
                            olist.Fields.Add("field2", SPFieldType.Text, false);
                            olist.OnQuickLaunch = true;
                            SPView newview = olist.DefaultView;
                            newview.ViewFields.Add("field1");
                            newview.ViewFields.Add("field2");
                            newview.Update();
                            olist.Update();
                            oweb.AllowUnsafeUpdates = false;
                            Console.WriteLine("List fields added");
                        }
                        else
                        {
                            Console.WriteLine("List already Exist");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            Console.ReadLine();

        }
    }

No comments:

Post a Comment