It is very hard to say what is wrong with your code without knowing more. I suggest you use a debugger and step through the code to make sure everything is executed correctly. You will probably encounter some oddities which will tell you where to look for errors.