Example how to add data to a SharePoint List using C#.
Add to a SharePoint list is as easy as adding data to any other data source.
First we need to create our connection string. It is best to using the web config file to store this;
<appSettings>
<add key ="SharePointSite" value="http://Developserver"/>
</appSettings>
?xml:namespace>
In the code behind we need to use the SharePoint namespace
using Microsoft.SharePoint;
using Microsoft.SharePoint.DirectorySoap;
using Microsoft.SharePoint.SoapServer;
And finally the code that will add the data from to your SharePoint List. There are some housekeeping items you will need to do; such as somehow ensuring that the data being sent is valid. You will need to ensure the field lengths fits the list items’ constraints. You cannot send Null’s to fields that do not accept null, etc…
It is also important to note that the field names are the names you first entered when creating the list. It is extreamly important that you have the exact field name. Not the display name!!! If you created the list with spaces in the field name you will have to replace the spaces with this - _x0020_. The SharePoint list I am adding to is a team task list. So the field names you will see are for my list. You can subsitue your field names with these. You can also read the list, extract the names and add each name dynamically.
/// <summary>
/// Submits form data to Sharepoint list
/// </summary>
/// <returns></returns>
protected bool ProcessForm(string Title)
{
try
{
string SharePointSite = ConfigurationManager.AppSettings["SharePointSite"].ToString();
// Since the SharePoing Title field can only hold 100 character
?xml:namespace>
if (Title.Length > 99)
{
Title = TaskTitleBox.Text.Substring(0, 100);
}
?xml:namespace>
using (SPSite oSiteCollection = new SPSite(SharePointSite))
{
?xml:namespace>
using (SPWeb oWebsiteRoot = oSiteCollection.OpenWeb("/"))
{
oWebsiteRoot.AllowUnsafeUpdates = true;
SPList oList = oWebsiteRoot.Lists["Team Workflow"];
SPListItem oListItem = oList.Items.Add();
oListItem["Title"] = Title;
oListItem["Status"] = "Submitted";
oListItem["Priority"] = PriorityBox.SelectedValue;
oListItem["Category"] = CategoryBox.SelectedValue;
oListItem["Planned"] = "Yes";
oListItem["Requested_x0020_By"] = oWebsiteRoot.AllUsers[Requestor];
oListItem["AssignedTo"] = oWebsiteRoot.AllUsers[AssignedTo];
oListItem["Body"] = DescriptionBox.Text;
oListItem["DueDate"] = DueDate(AddDays);
oListItem.Update();
}
}
?xml:namespace>
return true;
}
catch
{
return false;
}
?xml:namespace>
?xml:namespace>
}
?xml:namespace>
More Recent Sharepoint Articles:
Example how to read data from a SharePoint List using C#.Brief example on how to read data from a SharePoint list into a web form
Indenty ImpersonationExample of Indenty Impersonation
Get User's Windows login nameGet User's Windows login name
Exporting a datagrid object's data to ExcelExample on how to send data to Excel