jimminybob
jimminybob

Reputation: 1442

Get statuscode text in C#

I'm using a plugin and want to perform an action based on the records statuscode value. I've seen online that you can use entity.FormattedValues["statuscode"] to get values from option sets but when try it I get an error saying "The given key was not present in the dictionary".

I know this can happen when the plugin cant find the change for the field you're looking for, but i've already checked that this does exist using entity.Contains("statuscode") and it passes by that fine but still hits this error.

Can anyone help me figure out why its failing?

Thanks

Upvotes: 2

Views: 8350

Answers (4)

kmria
kmria

Reputation: 241

Try this

string Title = (bool)entity.Attributes.Contains("title") ? entity.FormattedValues["title"].ToString() : "";

When you are talking about Option set, you have value and label. What this will give you is the label. '?' will make sure that the null value is never passed.

Upvotes: 0

user2329121
user2329121

Reputation: 1

entity.FormattedValues work only for string display value.

For example you have an optionset with display names as 1, 2, 3, The above statement do not recognize these values because those are integers. If You have seen the exact defintion of formatted values in the below link

http://msdn.microsoft.com/en-in/library/microsoft.xrm.sdk.formattedvaluecollection.aspx

you will find this statement is valid for only string display values. If you try to use this statement with Integer values it will throw key not found in dictionary exception.

So try to avoid this statement for retrieving integer display name optionset in your code.

Upvotes: 0

James Wood
James Wood

Reputation: 17552

I've not seen the entity.FormattedValues before.

I usually use the entity.Attributes, e.g. entity.Attributes["statuscode"].

MSDN


Edit

Crm wraps many of the values in objects which hold additional information, in this case statuscode uses the OptionSetValue, so to get the value you need to:

((OptionSetValue)entity.Attributes["statuscode"]).Value

This will return a number, as this is the underlying value in Crm.

If you open up the customisation options in Crm, you will usually (some system fields are locked down) be able to see the label and value for each option.

enter image description here

If you need the label, you could either do some hardcoding based on the information in Crm.

Or you could retrieve it from the metadata services as described here.

Upvotes: 3

Greg Owens
Greg Owens

Reputation: 3878

To avoid your error, you need to check the collection you wish to use (rather than the Attributes collection):

if (entity.FormattedValues.Contains("statuscode")){
    var myStatusCode = entity.FormattedValues["statuscode"];
}

However although the SDK fails to confirm this, I suspect that FormattedValues are only ever present for numeric or currency attributes. (Part-speculation on my part though).

Upvotes: 3

Related Questions