Click here to Skip to main content
15,885,435 members
Articles / Web Development / ASP.NET
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
21 Apr 2015CPOL3 min read 14.7K   4   1
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)


Written By
Founder Across Time & Space
United States United States
I am in the process of morphing from a software developer into a portrayer of Mark Twain. My monologue (or one-man play, entitled "The Adventures of Mark Twain: As Told By Himself" and set in 1896) features Twain giving an overview of his life up till then. The performance includes the relating of interesting experiences and humorous anecdotes from Twain's boyhood and youth, his time as a riverboat pilot, his wild and woolly adventures in the Territory of Nevada and California, and experiences as a writer and world traveler, including recollections of meetings with many of the famous and powerful of the 19th century - royalty, business magnates, fellow authors, as well as intimate glimpses into his home life (his parents, siblings, wife, and children).

Peripatetic and picaresque, I have lived in eight states; specifically, besides my native California (where I was born and where I now again reside) in chronological order: New York, Montana, Alaska, Oklahoma, Wisconsin, Idaho, and Missouri.

I am also a writer of both fiction (for which I use a nom de plume, "Blackbird Crow Raven", as a nod to my Native American heritage - I am "½ Cowboy, ½ Indian") and nonfiction, including a two-volume social and cultural history of the U.S. which covers important events from 1620-2006: http://www.lulu.com/spotlight/blackbirdcraven

Comments and Discussions

 
QuestionHmmm, after reading this it seems that you have a little mistake in the <listcolumns> Pin
dzitam8-Jun-15 10:47
dzitam8-Jun-15 10:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.