Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

How to Create, Write to, and Read From Sharepoint 2010 Lists with C#

5.00/5 (1 vote)
21 Apr 2015CPOL3 min read 15K  
CRD Operations (there is no Updating method shown, so crud, it's not CRUD) with Sharepoint 2010

How to Create, Write To, and Read From Sharepoint 2010 Lists
(Another Sharepoint Pointer)

Sharepoint is a "land" of "Lis[z]tomania"

Here are some tips on how to conditionally create a list in code, then how to write to it, and how to read from it.

The first thing you have to do in any situation is "give it a name" so first give your List a name. To do so, put this within your WebPart class (prior to the constructor or any other methods):

C#
public string listTitle = "dPlatypus";

Give your list whatever name you want, but preferably something descriptive and unique.

Since we are going to (conditionally - that is, once and once only) create a Sharepoint list, write to the list and read from it, we should start by defining the structure of the list itself. We do this by creating a separate class, such as this one with the mundane name “ListColumns”:

C#
public class ListColumns
{
    public String li_requestDate { get; set; }
    public String li_paymentAmount { get; set; }
    public String li_payeeName { get; set; }
    public String li_remitAddressOrMailStop { get; set; }
    public String li_last4SSNDigitsOrITIN { get; set; }
    public String li_204SubmittedOrOnFile { get; set; }
    public String li_requesterName { get; set; }
    public String li_deptDivName { get; set; }
    public String li_phone { get; set; }
    public String li_email { get; set; }
}

Of course, you will have different members of your list, and may use data types other than string (such as Date, which I could have used for li_requestDate, and Bool, which I could have used for li_204SubmitedOrOnFile), although that (String) is what I stuck with in this situation. The interesting parts will take place when the user does something like clicking a "Save" button. To create such a button, set it up, and add a click handler to it, you can add this somewhere in a WebPart's overridden CreateChildControls() method:

C#
Button btnSave = new Button();
btnSave.Text = "Save";
btnSave.Click += new EventHandler(btnSave_Click);
this.Controls.Add(btnSave);

Alternatively, you can put this code in the *.ascx.cs file (the one that inherits from UserControl), in the Page_Load() handler:

public partial class DPSVisualWebPartUserControl : UserControl
{
    static Guid siteID = SPContext.Current.Site.ID;
    private String siteUrl = "https://financial.ucsc.edu";
    private string listTitle = "DirectPayFormFields3";
    List<ListColumns> listOfListItems = null;


    protected void Page_Load(object sender, EventArgs e)
    {
        base.OnPreRender(e);
    // create the controls/elements dynamically here
    . . .

You could implement that event handler something like this:

C#
private void btnSave_Click(object sender, EventArgs e)
{
    try
    {
        ConditionallyCreateList();
        SaveInputToList();
        List<ListColumns> listOfListItems = ReadFromList();
        // Now do something with listOfListItems, such as generate a PDF report using iTextSharp
    }
    catch (Exception ex)
    {
        message.Text = String.Format("Exception occurred: {0}", ex.Message);
    }
    message.Text = "There ain't no Bishop like Elvin Bishop";
}

The code in the Save button’s event handler creates the list if it does not already exist, then saves values the user has entered into a record/row/instance of that list, and then reads them right back out again and does something with the data (in the case we will show, generates a PDF file from the contents). You can, of course, read only a subset of the data based on whatever criteria you want (content-based, or time-based, or what have you).

Here are the methods that event handler calls, broken down into function (ConditionallyCreateList for creating, SaveInputToList for writing, and GeneratePDF for reading):

Conditionally Create a List

For creation of the list, look at ConditionallyCreateList():

C#
private void ConditionallyCreateList()
{
    SPWeb site = SPContext.Current.Web;
    // Check to see if list already exists; if so, exit
    if (site.Lists.TryGetList(listTitle) != null) return;

    SPListCollection lists = site.Lists;
    SPListTemplateType listTemplateType = new SPListTemplateType();
    listTemplateType = SPListTemplateType.GenericList;
    string listDescription = "This list retains vals inputted for Section 1 and 2 of the Direct Payment form";
    Guid ListId = lists.Add(listTitle, listDescription, listTemplateType);

    SPList list = site.Lists[ListId];
    list.OnQuickLaunch = true;
    list.Fields.Add("RequestDate", SPFieldType.Text, false); // or SPFieldType.DateTime
    list.Fields.Add("PayeeName", SPFieldType.Text, false);
    list.Fields.Add("RemitAddressOrMailStop", SPFieldType.Text, false);
    list.Fields.Add("Last4SSNOrITIN", SPFieldType.Text, false);
    list.Fields.Add("204SubmittedOrOnFile", SPFieldType.Text, false); // or SPFieldType.Boolean
    list.Fields.Add("RequesterName", SPFieldType.Text, false);
    list.Fields.Add("DeptDivName", SPFieldType.Text, false);
    list.Fields.Add("Phone", SPFieldType.Text, false);
    list.Fields.Add("Email", SPFieldType.Text, false);

    list.Update();
}

This method returns/does nothing if the list already exists.

Write Values to a Sharepoint List

For writing to the list, note SaveInputToList():

C#
private void SaveInputToList()
{
    try
    {
        using (SPSite site = new SPSite(siteUrl))
        {
            using (SPWeb web = site.RootWeb)
            {
                SPList list = web.Lists[listTitle];
                SPListItem spli = list.Items.Add();
                spli["Title"] = String.Format("List item created {0}",               
SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now));
			    // Save TextBox vals like this
                if (null != boxRequestDate)
                {
                    if (String.IsNullOrEmpty(boxRequestDate.Text))
                    {
                        spli["RequestDate"] = DateTime.Today.ToShortDateString();
                    }
                    else
                    {
                        spli["RequestDate"] = boxRequestDate.Text;
                    }
                }
                else // if it IS null, give it a default val, too
                {
                    spli["RequestDate"] = DateTime.Today.ToShortDateString();
                }

                if (null != boxPaymentAmount)
                {
                     if (String.IsNullOrEmpty(boxPaymentAmount.Text))
                     {
                         spli["PaymentAmount"] = "[left blank]";
                     }
                     else
                     {
                         spli["PaymentAmount"] = boxPaymentAmount.Text;
                     }
                }
                else 
                {
                    spli["PaymentAmount"] = "[left blank]";
                }
    			   // . . .
	    		   // Save boolean vals like this:
			    if (null != rbUSCitizenOrPermResY)
                {
                    spli["PayeeIsUSCitizenOrResident"] = rbUSCitizenOrPermResY.Checked;
                }
               
                spli.Update();
            }
        }
    }
    catch (Exception ex)
    {
        String s = String.Format("Exception is {0}", ex.Message);
    }
}

Read Values From a Sharepoint List

Finally, for reading the values back out of the list, recall that the Save button assigned the values of a method to a list of a type called ListColumns, like so:

C#
List<listcolumns> listOfListItems = ReadFromList();

And here is that method showing how to read the values back out of the list:

C#
private List<listcolumns> ReadFromList()
{
    List<ListColumns> lcList = new List<listcolumns>();

    using (SPSite site = new SPSite(siteUrl))
    {
        using (SPWeb web = site.RootWeb)
        {
            SPList list = web.Lists[listTitle];
            SPListItemCollection SpListColl = list.Items;
            foreach (SPListItem item in SpListColl)
            {
                ListColumns lc = new ListColumns();
                if (null != item["Title"])
                {
                    if (!(String.IsNullOrEmpty(item["RequestDate"].ToString())))
                    {
                        lc.li_requestDate = item["RequestDate"].ToString();
                    }
                    // . . . and so forth
                
                    lcList.Add(lc);
                }
            }
        } // using (SPWeb
    } // using (SPSite
    return lcList;
}

So now that you've got the list items in the List of ListColumns, you can do whatever you want with them (within reason, of course; please do not make a pet of them, try to get them to run for public office, or represent a new gender classification).

Cravat Eruptor

If you got to here and found you wasted your time reading this drivel, take out your frustration by severing your bowtie with the scraggly tip of your neckbeard. Or not; it's up to you, I guess.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)