You've just quoted a lengthy piece of code, but given no indication what the
problem is, nor where it is.
Put a breakpoint at the start of the code and step it through. This will
show you where it's going wrong and what it's done before it goes wrong.
Once you have much more precise information, get back to the group with a
more specific question.