Tuesday, August 10, 2010

Sample code to Create a Custom List Using Object Model in Sharepoint 2007

Listed below are the Sharepoint site components and their corresponding object in the sharepoint object model.
Sharepoint Site Architecture ComponentObject in Sharepoint Object Model
Site CollectionSPSite
List CollectionSPListCollection
List Field CollectionSPFieldCollection
List FieldSPField
List Item CollectionSPListItemCollection
List ItemSPListItem
Steps to create a new Sharepoint List:
  1. Open Visual Studio. Create a new Windows Forms project.
  2. Add a textboxes, one to accept the name of the site collection and another to accept the name of the new site to be created under the site collection.
  3. Add a button that creates the new site.
  4. Add reference to Microsoft.Sharepoint dll. This dll is represented by the name Windows Sharepoint Services in the Add Reference dialog box.
  5. Add the namespace of Microsoft.Sharepoint dll like this.
    • using Microsoft.Sharepoint;
  6. In the button click event, open the site collection.
    • SPSite siteCollection = new SPSite(txtSiteCollectionUrl.Text);
  7. Now open the top level site of the site collection.
    • SPWeb site = siteCollection.OpenWeb();
    • If you want to open a different site under the site collection other than the top level site, you can use the overloaded methods of the OpenWeb() method that accepts the name of the site as argument.
  8. The Lists property present in the SPWeb object will return all the lists that are present in that site as an SPListCollection object
    • SPListCollection listCollection = site.Lists;
  9. In order to add a new list, use the add method of the SPListCollection object.
    • listCollection.Add(“listname”, “list description”, SPListTemplateType.GenericList);
    • Note that the third argument accepts the template in which the list should be created. GenericTemplate represents the custom list. We can choose the template we need from the SPListTemplateType enum.
  10. Close and dispose and the site and site collection
    • site.dispose();
    • siteCollection.close();
The complete code can be found below..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;
namespace WindowsFormsApplication1
public partial class Form1 : Form
public Form1()
SPSite siteCollection;
SPWeb site;
private void btnCreateSite_Click(object sender, EventArgs e)
siteCollection = new SPSite(txtSiteCollection.Text);
site = siteCollection.OpenWeb();
SPListCollection listCollection = site.Lists;
listCollection.Add(txtListName.Text, “list description”, SPListTemplateType.GenericList);
catch (Exception)
{ }

No comments:

Post a Comment