Whenever you see an error telling you that an Object is not set to an instance, in C#, this is telling you that something in your code is unassigned. In other words you have, somewhere in your code, a null reference. We're not going to be able to tell you where this is because we don't have all your code.
The good news is, this is very easy to find. There are a couple of ways to do this.
- Use the stack trace. When you encounter an error, you will get a stack trace as part of that error. Use System.Debug.Diagnostics to write out the whole exception (don't trim it to just the message).
- The second approach, and the one I would prefer to use, is to actually debug the code. Put a breakpoint at the start of this function, and step through it line by line. Before you execute a line, check to make sure that any properties on that line are not null. You can easily check this by hovering your mouse over it, and seeing what pops up in the tooltip.
To be honest, your first instinct should be to debug your code. It's much easier to do that than to go onto a website and post the code hoping that someone is going to be able to spot what's wrong for you. It could take you a couple of minutes to accomplish what you could be waiting for a couple of hours, to get a reply off a website.