I have a library that allows multiple folder content types. I am grouping the folders by content type but I don't want the group heading to say Content Type: whatever. Instead, I created a hidden column Study Type and I have an ItemAdding event receiver set this field when an item is created. This works fine.
Now it occurred to me that the client may want to edit the folder and my event receiver must still set the proper fields to new values. Easy, I thought. I would just add an ItemUpdating event to my receiver have it execute the same code and all done. But this doesn't work. Below is my code.
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
execute(properties);
}
public override void ItemUpdating(SPItemEventProperties properties)
{
base.ItemUpdating(properties);
execute(properties);
}
public void execute(SPItemEventProperties properties)
{
base.EventFiringEnabled = false;
SPList objlist = properties.List;
System.Diagnostics.Trace.WriteLine("list " + objlist);
string contentTypeName;
SPContentType contentType;
//initiolise(properties);
if (objlist.Title == "In-House Studies" || objlist.Title == "CRO Studies" || objlist.Title == "Studies by Collaborators")
{
string titleInternalName = objlist.Fields["Study Type"].InternalName;
string inVivoInVitro = objlist.Fields["In-Vivo/In-Vitro Type"].InternalName;
string temp;
try
{
contentTypeName = properties.AfterProperties["ContentType"].ToString();
contentType = objlist.ContentTypes[contentTypeName];
try
{
if (contentType.Name == "In-Vitro Experiment")
{
properties.AfterProperties[titleInternalName] = "A.In-Vitro Experiment";
temp = objlist.Fields["In-Vitro Type"].InternalName;
properties.AfterProperties[inVivoInVitro] = properties.AfterProperties[temp];
}
else if (contentType.Name == "In-Vivo Study")
{
properties.AfterProperties[titleInternalName] = "B.In-Vivo Study";
temp = objlist.Fields["In-Vivo Type"].InternalName;
properties.AfterProperties[inVivoInVitro] = properties.AfterProperties[temp];
}
else if (contentType.Name == "CRO Study")
{
properties.AfterProperties[titleInternalName] = "A.CRO Study";
}
else if (contentType.Name == "Generic Folder")
{
properties.AfterProperties[titleInternalName] = "C.Generic";
}
else
{
properties.AfterProperties[titleInternalName] = "D.Document";
}
}
catch (Exception)
{
properties.AfterProperties[titleInternalName] = "D.Document";
}
}
catch (NullReferenceException)
{
properties.AfterProperties[titleInternalName] = "D.Document";
}
}
base.EventFiringEnabled = true;
}
Now my understanding is the AfterProperties contain the new values for the item in an ItemUpdating event receiver, however
contentTypeName = properties.AfterProperties["ContentType"].ToString();
fails with a null reference exception. Why doesn't my code work with an ItemUpdating event receiver?
properties.AfterProperties["ContentTypeId"].ToString();
is present. For some reason, that field may not be available.