Inserting value into SharePoint list programmatically:
If we have list already created in SharePoint and want to add / insert value pro grammatically into the list then will use the below code.
Suppose we have a list called UserAccess and it has FirstName, LastName , Email and Status columns and we want to insert value to the list then we can use below code
protectedvoid Page_Load(objectsender, EventArgs e)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite spSite = new
SPSite(SPContext.Current.Web.Site.WebApplication.Sites[0].Url))
{
spSite.AllowUnsafeUpdates = true;
using(SPWeb spWeb = spSite.OpenWeb())
{
spWeb.AllowUnsafeUpdates = true;
SPList spList = spWeb.Lists.TryGetList("UserAccess");
varitemId = 0;
SPListItemlistItem = null;
if(itemId == 0)
{
listItem = spList.AddItem();
}
else
{
listItem = spList.GetItemById(itemId);
}
listItem["FirstName"] = txtFirstName.Text;
listItem["LastName"] = txtLastName.Text;
listItem["Email"] = txtEmail.Text;
listItem["Status"] = "Pending";
listItem.Update();
spWeb.AllowUnsafeUpdates = false;
}
spSite.AllowUnsafeUpdates = false;
}
});
}