Tuesday, March 29, 2011

Programmatically attach workflow to List Item of SharePoint List

In this article, I will explain how to programmatically attach workflow to list item of SharePoint list. Workflow can be attached to a list while adding new item or updating the item.
Following method can be used to attach workflow to list item programmatically
Public void AttachWorkflowToListItem (string ListName, int ListItemID, SPSite oSite, SPWeb oWeb)
{
oWeb.AllowUnsafeUpdates = true;
SPList _ListName = oWeb.Lists [ListName];
SPListItem _ListItem = _ ListName.GetItemById (Convert.ToInt32 (ListItemID));
//Creates and starts a new workflow instance on a specified list item
SPWorkflowManager _manager = oSite.WorkflowManager;
// collect all workflows which are associated with the List
SPWorkflowAssociationCollection _associationCollection = _ ListName.WorkflowAssociations;
LookupAndStartWorkflow (_ListItem, _manager, _associationCollection, "WorkflowID");
}
Private static void LookupAndStartWorkflow (SPListItem ListItem, SPWorkflowManager manager, SPWorkflowAssociationCollection AssociationCollection, string WorkflowId)
{
//iterate workflow associations and lookup the workflow to be started
Foreach (SPWorkflowAssociation association in AssociationCollection)
{
//if the workflow association matches the workflow we are looking for,
//get its association data and start the workflow

if (association.Name.Equals(WorkflowId))
{
//get workflow association data
String data = association.AssociationData;
//start workflow
SPWorkflow wf = manager.StartWorkflow (ListItem, association, "open tag Data close tag Data", true);
break;
}
}
}

No comments:

Post a Comment