Below is the code to insert item into a SharePoint list.
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace customlist
{
//Below Guid can be genrated from from Tools menu of Visual Studio and then choose create GUID
[Guid("EABAFAC0-0288-4292-9007-B8AAB8BC45DA")]
public class WebPart1 : System.Web.UI.WebControls.WebParts.WebPart
{
TextBox oTextTitle;
TextBox oTextName;
TextBox oTextDesignation;
Label oLabelMessage;
Button oButtonSubmit;
//Constructor
public WebPart1()
{
}
//Adding controls in below code block
protected override void CreateChildControls()
{
base.CreateChildControls();
oTextTitle = new TextBox();
this.Controls.Add(oTextTitle);
oTextName = new TextBox();
this.Controls.Add(oTextName);
oTextDesignation = new TextBox();
this.Controls.Add(oTextDesignation);
oLabelMessage = new Label();
this.Controls.Add(oLabelMessage);
oButtonSubmit = new Button();
oButtonSubmit.Text = "Submit";
oButtonSubmit.CssClass = "ms-ButtonHeightWidth";
this.Controls.Add(oButtonSubmit);
oButtonSubmit.Click += new EventHandler(oButtonSubmit_Click);
}
//Below Code block will execute when user will click on Submit Button
void oButtonSubmit_Click(object sender, EventArgs e)
{
if (oTextTitle.Text.Trim() == "" || oTextName.Text.Trim() == "" || oTextDesignation.Text.Trim() == "")
{
oLabelMessage.Text = "You must specify a value for this required field";
}
else
{
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = SPContext.Current.Web;
SPList myList = myWeb.Lists["your list name"];
SPListItem myListItem = myList.Items.Add();
myListItem["Field1/Column1"] = oTextTitle.Text.ToString();
myListItem["Field2/Column2"] = oTextName.Text.ToString();
myListItem["Field2/Column2"] = oTextDesignation.Text.ToString();
myWeb.AllowUnsafeUpdates = true;
myListItem.Update();
myWeb.AllowUnsafeUpdates = false;
oLabelMessage.Text = "Recorded inserted";
oTextTitle.Text = "";
oTextName.Text = "";
oTextDesignation.Text = "";
oTextTitle.Focus();
}
}
For more about sharepoint please visit : http://sharepointcafe.net