Tuesday 26 March 2013

Adding details to database table using SharePoint List event receiver

Here's a sample code to give you idea about how to add item details to database table using SQL stored procedure and ItemAdded event receiver,




    class myClass : SPItemEventReceiver
    {
        public override void ItemAdded(SPItemEventProperties properties)
        {
            try
            {
                this.DisableEventFiring();

                AddToDataBase(properties);
            }
            catch (Exception ex)
            {
                //log here
            }
            finally
            {
                this.EnableEventFiring();
            }
        }

private void AddEntryToDataBase(SPItemEventProperties properties)
        {
using (SqlConnection con = new SqlConnection(dc.Con))
using (SqlCommand cmd = new SqlCommand("sp_Add_ListItem", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Title", SqlDbType.VarChar).Value = properties.ListItem.Title.ToStrinng;
cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = properties.ListItem.Name.ToString;

con.Open();
cmd.ExecuteNonQuery();
}
}
}

Check this link on MSDN for more information or just leave a comment below,

http://msdn.microsoft.com/en-us/library/ms437502(v=office.14).aspx

2 comments:

  1. How would you write the Stored Procedure and match up values

    ReplyDelete
  2. Thanks, I am still confused
    using (SqlConnection con = new SqlConnection(dc.Con)) "what is dc? connection string? and what is Con

    another issues what I got is a null for coming back.

    when I run this a null come back

    SPSite CurrentSite = new SPSite(properties.SiteId);
    SPWeb CurrentWeb = CurrentSite.OpenWeb(properties.RelativeWebUrl);
    SPList CurrentList = CurrentWeb.Lists[properties.ListId];
    //The line below is where the error is

    SPListItem item = CurrentList.GetItemById(properties.ListItemId);

    I am calling ItemAdding()



    ReplyDelete