Thursday, August 08, 2013

Finding ListItem Id in ItemAdding event

Recently I wanted to work on the scenario where I wanted to find the "ListItem" Id in SharePoint list while "ItemAdding" event.

Its something like generating the auto Id or unique list Item id to be used in the custom application page.(.ASPX)
I googled and binged and I was informed  the stories which telling me "You can't be get ListItem Id on synchronous event,other message goes like "You can get null value or index value 0.

So my tendency is not allowing me the things goes off just like that . I spent few minutes to get the logic involved in the situation  to find the answer on my own.

In an half hour of time spent on this , I came up with the solution which will work on to finding the "ListItem Id" in ItemAdding event as well as when you delete the record from the List,
still you'll get the unique list Item id.

Simple thoughts on it,

Step 1: ( put logic in synchronous event receiver)

  1. Get the all rows in the SPListItemCollection (Assign to DataTable)
  2. Loop all Rows in the DataTable
  3. Add the rows which sharing the name "ID" into Generic List.
  4. Find the Max value in Generic list
  5.  Save this max value in PropertyBag
  6. Retrieve Property Bag value in your application page.
  7. Last but not least -> Add value +1 to your retrieved PropertyBag Value to predict the new ListItemId.

List arr = new List();
You have to update the PropertyBag in every event of the receiver to get updated value from the SharePoint List.

 public override void ItemAdded(SPItemEventProperties properties)
       {
           SPWeb web = properties.Web;
           SPSecurity.RunWithElevatedPrivileges(delegate()
           {
                
                   SPList list = properties.List;
                   DataTable cols = list.Items.GetDataTable();
                   //int MaxVal =  Convert.ToInt32(cols.Compute("max(ID)", String.Empty));
                   if (cols.Rows.Count > 0)
                   {
                       foreach (DataRow row in cols.Rows)
                       {
                           arr.Add(Convert.ToInt32(row["ID"]));
                       }
                   }
                   var c1 = arr.Max();
                   properties.Web.Properties["UniqueVal"] = c1.ToString();
                   properties.Web.Properties.Update();
                   web.Update();
 
           });
       }
 public override void ItemDeleted(SPItemEventProperties properties)
       {
           int deletedId = properties.ListItemId;
           SPList list = properties.List;
           DataTable cols = list.Items.GetDataTable();
           int MaxVal =  Convert.ToInt32(cols.Compute("max(ID)", String.Empty));

           if (deletedId == MaxVal)
           {
               properties.Web.Properties["UniqueVal"] = Convert.ToInt32(deletedId).ToString();
           }
          

       }