Here's one of my favorite samples floating around in the CRM world:
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!
- 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.
- Even setting it to null is nonsense when setting it to crmForm.all.customerid.DataValue afterwards.
- The DataValue property is null if no value is stored in a lookup field. Therefore accessing lookup 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.
- If there is a value stored in the lookup field, then lookup won't be null. The only way it could be null is you setting it to null in code (crmForm.all.customerid.DataValue = 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.