Skip to content
Microsoft Dynamics 365

CRM MVP Michael Höhne is our guest blogger today. You can read more by him on his blog.

Here’s one of my favorite samples floating around in the CRM world:

         image

I have seen this code numerous times and before explaining what’s wrong (actually everything is wrong, besides the alerts), I want to tell you a story, which is also told by the above code.

You enter a mall and buy a basket, because you want to see if there is an apple in it. However, after leaving the mall you throw the basket away without using it. Back at home you search for an existing basket, take the first apple out of it and try to figure out if it is red. You then wonder why you cannot determine the color, because you forgot to check if there was a basket at all.

That’s what the code does!

  1. There is no reason to initialize the lookup variable with a new Array when setting it to null in the next line. This is the basket you are buying and instantly throwing away.
  2. Even setting it to null is nonsense when setting it to crmForm.all.customerid.DataValue afterwards.
  3. The DataValue property is null if no value is stored in a lookup field. Therefore accessing lookup[0] results in a null reference exception if DataValue equals null, because the lookup variable then will be null as well. It is the same as grabbing the first apple from a basket without having the basket first.
  4. If there is a value stored in the lookup field, then lookup[0] won’t be null. The only way it could be null is you setting it to null in code (crmForm.all.customerid.DataValue[0] = null), but that would be like writing var circle = null and wondering why circle.radius doesn’t work.

To summarize: samples are great. But be sure to understand what they do first.

Cheers,

Michael Höhne


We're always looking for feedback and would like to hear from you. Please head to the Dynamics 365 Community to start a discussion, ask questions, and tell us what you think!