Monday, May 28, 2012

Insert new item to sharepoint list programmatically


Here is steps to add new item to sharepoint list programmatically.
- Declare variable which hold the newly created item id.
int _Int_ID = 0;

- Follow the steps to insert new item into your sharepoint list.


- Create new instance of site with your current application
using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
{

- Create new web instance and open web for current application
        using (SPWeb web = site.OpenWeb())
        {

- Create new list object and get your list
                SPList list = web.Lists["Your List Name"];

- Set allowunsafeupdates for web & site to true
                site.AllowUnsafeUpdates = true;
                web.AllowUnsafeUpdates = true;

- Create new list item object and add new item for newly created list object
                SPListItem item = list.Items.Add();
- Assign value for newly created item
                item["Title"] = "Title1";
- Update item which will add new item to list
                item.Update();
- if you want to manipulate on newly created item then you can get id of the newly created item by following way
                itemId = item.ID;
        }
}

-That’s it for adding new item to your sharepoint list.

No comments:

Post a Comment