Create SharePoint List with Code and CAML

CAML is an XML based language used for access SharePoint objects like List, Library, Content Type, Site Columns.

To know more about CAML Query, please visit my another blog post Learn CAML Query step by Step
CAML comes under declarative and the code that we write using SharePoint server object model comes under imperative programming.

In SharePoint a programmer can implement things in both ways either by imperatively i.e. using code or declaratively i.e. using CAML.

So let’s demonstrate this scenario by example.

I will create a List by using SharePoint server object model and by using CAML.

First I will create a List using SharePoint server object model code.

1. Create an empty SharePoint project in Visual Studio (I have used VS2012)

2. Right click on Feature folder in Solution Explore and select “Add Feature”

3. Rename this feature to “CreateListFeature”

4. Right click on newly Added Feature and select “Add event Receiver”

5. Write below code on Feature Activated

public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            using (SPSite oSPSite = new SPSite("http://server-url"))
            {
                SPWeb oSpWeb = oSPSite.RootWeb;
                oSpWeb.Lists.Add("My New List", "New List Created by Code", SPListTemplateType.GenericList);
            }
        }

6. Right click on your project and deploy it.

7. Go to Site Settings ->Manage Site Features (Within Site Actions)

8. Search for your feature, and make sure Feature is activated.

9. If not, then activate it.

1. Go to Site Actions -> View All site Content

1. You will find your newly created list.



Note: You can’t activate this feature more than once, as it will try to create the same list again, which will cause an error. For this you need to check the existence of List and then create it on Feature Activated.


Now I will create List using CAML.
Right click on Solution and Select Add New Item
Select "List" from installed template.


You may write below CAML in manifest file i.e. Elements.xml file.

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <ListInstance Title="MyNewListWithCAML"
                OnQuickLaunch="TRUE"
                TemplateType="100"
                FeatureId="ACDD47D6-B1CD-4F0D-B633-4EB7860600DC"
                Url="Lists/MyNewListWithCAML    "
                Description="My List Instance">
  </ListInstance>

</Elements>

Previous Blog

Comments

Popular

Top 8 C# 6.0 Features

SharePoint Interview Questions and Answers

Calling ASP.Net WebMethod using jQuery AJAX

What is Cloud Computing - A guide for beginners