Tuesday, September 27, 2011

Adding a lookup field to a list programatically

Alright, I had a requirement where a lookup field needs to be added to list referencing another list's ID column. I managed to do this using the below code. You can understand without explaining all the inner details, I think.

//Adding a lookup column to link the item to the related item
var list = web.Lists["LookupListName"];
thisList.Fields.AddLookup("LookupFieldName", list.ID , web.ID, true);
SPFieldLookup lookupField = reportThisList.Fields.GetField("LookupFieldName" 
                                 as SPFieldLookup;
lookupField.LookupField = "ID";
//Adding indexing to enable "CACADE" delete of this list items
lookupField.Indexed = true;
//CASCADE - deletes all the related items in this list when an item is deleted.
lookupField.RelationshipDeleteBehavior = SPRelationshipDeleteBehavior.Cascade;
lookupField.Update(true);

After doing this above code, you will see a new column in the list (thisList). Here is a preview












If an item is deleted from the related list("LookupListName"), all the related items in thisList would get deleted automatically.

I know this might not give you a clear explanation. If you need more details, just add a comment, I will try to explain it in more detail.

Thanks
Senthil S

Adding list event receivers programatically

Recently, I was in a situation where event receivers needs to be attached to a SPList. Here is how it can be added dynamically using the api.



Like the above code, we can add the event receivers for any list event.

I have not tried the same for any other event receivers, but I am guessing it should be working the same way.

Thanks
Senthil S

Saturday, September 10, 2011

Check whether alerts are turned on for a Web Application

Even, if a user has an alert created for a list or list item or any other kind of alert, the alerts need to be turned on for the particular web application from the Central Admin.

How do we check whether it is turned on or not?

  • Go to Central Admin -> Application Management -> Manage Web Applications
  • Select the Web Application and select General Settings option from the tool bar
  • Make sure "Alerts on this server are "Tuned On"

Hope this helps someone

Senthil