Create SharePoint Survey list programmatically and set properties

We know, Surveys are very important for many organizations, by conducting survey they take the decisions based on the responses. SharePoint is providing a good flexibility for Surveys.
I have a user requirement, user will deploy a single WSP file in different Servers and that WSP file should deploy all the SharePoint Lists in that environment. Creating SharePoint survey list programmatically is very easy. Lets see how to create a SharePoint survey list programmatically and set survey list properties.

C#.NET Code Behind:

  //Adding Survey List to SharePoint site
  SPListTemplate objTemplate = web.ListTemplates["Survey"];
  Guid objGuid = web.Lists.Add(strListName, string.Empty, objTemplate);
  SPList objSurvey = web.Lists[strListName];

  //Changing the title of the SharePoint List
  objSurvey.Title = Constants.ListTitles.VotesForLecturers;

  //Changing the SharePoint Survey list property to allow multiple responses
  objSurvey.AllowMultiResponses = true;

  //Adding lookup column to survey List Programmatically
  SPList lstEmployees = web.Lists[Constants.ListNames.Employees];
  var Employees = objSurvey.Fields.AddLookup("Employee", lstEmployee.ID, true);
  SPFieldLookup EmployeesField = (SPFieldLookup)objSurvey.Fields[Employees];
  EmployeesField.LookupField = lstEmployees.Fields["Employee Name"].InternalName;

  //Creating and Adding Question to Survey List Programmatically with rating scale
  strQuestionTitle = "Lecturer Skills";

  //Adding Question Options
  StringCollection strQuestions = new StringCollection();
  strQuestions.Add("Share Knowledge");
  strQuestions.Add("Provide guidance");

  //Adding Question field to survey list
  objSurvey.Fields.Add(strQuestionTitle, SPFieldType.Choice, true, false, strQuestions);

  //Adding text field to Survey list
  objSurvey.Fields.Add("Comments", SPFieldType.Note, false);

You can also Add Rating scale to the survey List.

Before your code use "AllowUnsafeUpdates = true" for updating the web and then after adding the Survey list to web, reset this property back to false.

Before running this code, you have to ensure the "Team Collaboration Lists" feature is activated.

Activating Team Collaboration Lists Feature: to activate this feature, navigate to 'Site settings' > 'Site Features' > scroll down the list and ensure this feature is active.

You have successfully added a survey list to SharePoint site after successfully deploying the code. you can navigate to site content to see this list.

Hope this article is helpful for you.

Sudheer Gangumolu

I'm a Software Analyst / Developer / Blogger, having good experience in working with different flavors & Customization of SharePoint (i.e.,SP O365 / 2013 / 2010 / 2007) and .Net Apps. Currently, working on SharePoint 2013 / SharePoint O365. Guiding people on my technologies.

    Blogger Comment
    Facebook Comment


Post a Comment