Programmatically Change the Status of a Dynamics CRM Record

Roshan Mehta, 27 June 2012

The Microsoft Dynamics CRM 2011 SDK provides a simple way to change the status of a record for any entity using the SetStateRequest object. Changing the status involves modifying the statuscode and/or statecode fields of a record depending on whether or not a status reason needs to be set when deactivating a record.

 Programmatically Change the Status of a Dynamics CRM Record

Let’s assume we have a new Lead created for “Roshan Mehta” which we want to disqualify because he is no longer interested in doing business with our company. I have built a simple Console Application which will deactivate the Lead record and set the status reason to “No Longer Interested” using the SetStateRequest object.

Guid leadId = new Guid("D020F344-A470-E111-B9DA-00155D04DC01"); 

SetStateRequest request = new SetStateRequest
{
    EntityMoniker = new EntityReference("lead", leadId),
    State = new OptionSetValue(2),
    Status = new OptionSetValue(6)
};

_sdk.Execute(request);

Looking at the code above, we can see that there are three important pieces of information:

EntityMoniker – This property is an EntityReference object which tells the CRM platform which record we want to deactivate. We need to pass in the entity logical name and the Id (GUID).

State – The new state of the record. For the lead entity, we can set one of three state values. These are Open, Qualified, or Disqualified. In our case, we want to set the record to Disqualified. This property is of OptionSetValue type.

Status – The new status of the record. For the Disqualify state, there are four status values: Lost, Cannot Contact, No Longer Interested, and Cancelled. In our case, we want to set the record to No Longer Interested. This property is of OptionSetValue type.

In the code snippet above, we pass integer values into the OptionSetValues for our State and Status properties but how do we know which values to pass in?

 Programmatically Change the Status of a Dynamics CRM Record

Here we can see the definition of the Status Reason field on the Lead entity. We know we want to disqualify our lead and we can see that it is the third item in the drop-down-list. The State property always starts with a “zero index” which means that Open = 0, Qualified = 1, and Disqualified = 2. We also know that our Lead is “No Longer Interested”. In the field definition, we can select this option and click on Edit to see that is integer value is “6”.

 Programmatically Change the Status of a Dynamics CRM Record

Using these values, we can run our code and see the following result. 

 Programmatically Change the Status of a Dynamics CRM Record