Without having a lot more information about the situation it's quite impossible to say why the code isn't running as expected.
In order to investigate (any) situation, it's critical to master using the debugger. Try placing breakpoints on different code lines, investigate the values of the variables etc. This way you learn how to see the program flow and why it behaves as it does.
As a starting point, have a look at
Get started with the debugger - Visual Studio | Microsoft Docs[
^]