How to fix System.NullReferenceException: 'Object variable or With block variable not set.'

Stephen H. Jones 40 Reputation points
2024-08-09T20:54:45.98+00:00

Working Visual Studio Pro 2019, project is .NET Framework 4.72

I have a design window with several numeric input objects. I deleted one and recreated it but now I get this error when I test the solution. It builds just fine and shows no errors in the code windows but when I open this window in the app, it fails with this message pointing to the code of this newly recreated object. I have tried everything I can think of to cure this issue but nothing seems to work.

Please HELP!

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
5,449 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 57,476 Reputation points
    2024-08-09T20:59:14.73+00:00

    You'll need to share the code with us along with the exception details including the message and stacktrace. Without that we have no idea what is wrong.

    Just off the top of my head you most likely have a field that isn't set and your code is referencing it which triggers a NRE. In general you should only ever delete things via the designer. If you deleted it in code then that tends to lead to problems like this. But, again, just a guess with no other information.

    When the error occurs you'll get thrown into the debugger. At that point you have the exact line that is failing and one of the instances on that line is null. You then need to figure out why. It could be because you deleted some controls or it could be something completely unrelated. The debugger will show you what is bad though. Fix the code by ensuring you either handle cases where the instance is null or by ensuring the value is never null.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.