Click here to Skip to main content
14,360,820 members
Rate this:
Please Sign up or sign in to vote.
Basically i get the error message:

Object reference not set to an instance of an object

It occurs on this line of code:
selectedItem = (string)control.Content;



Everytime i run the code, basically the code below is the top part of the code that is within the searchButton_Click.

The error message comes up when i click search without chosing an option within the combobox. When i chose an option it runs fine.

string queryFilter = "";
            string query = "Select * from SpecialMoment";
            ContentControl control;
            string selectedItem;

            control = categoryComboBox.SelectedItem as ContentControl;
            selectedItem = (string)control.Content;
            if (selectedItem == "Entertainment")            // Entertainment Option
            {
                queryFilter = " GenreID  in ('2',  '3', '11',  '14')";
            }
            else if (selectedItem == "Food and Drink")
            {
                queryFilter = " GenreID = '7'";
            }
            else if (selectedItem == "Health and Beauty")
            {
                queryFilter = " GenreID = '5'";
            }
            else if (selectedItem == "Shopping")
            {
                queryFilter = " GenreID in ('1', '6', '9', '10', '13')";
            }
            else if (selectedItem == "Sports")
            {
                queryFilter = " GenreID in ('4', '8', '12')";
            }
            else if (selectedItem == "Travel")
            {
                queryFilter = " GenreID = '15'";
            }
            else if (selectedItem == null)
            {

            }
Posted
Rate this:
Please Sign up or sign in to vote.

Solution 1

You have answered your own question!

The key is this line of code
control = categoryComboBox.SelectedItem as ContentControl;

If you haven't selected an option then SelectedItem will be null, resulting in the error message
Quote:
Object reference not set to an instance of an object


Put in a check against SelectedItem being set before attempting to use it.
   
Comments
Maarten Kools 25-Feb-14 15:44pm
   
To add to that: SelectedItem might actually be a valid object, but not a ContentControl. The as operator[^] in this case will cast the object to a ContentControl, if possible, and otherwise return null.
CHill60 25-Feb-14 15:46pm
   
Good point!
Chris_Burns 25-Feb-14 16:10pm
   
How would i do that? could you write the code for me? Not very experienced unfortunately :(
Sergey Alexandrovich Kryukov 25-Feb-14 16:51pm
   
I voted 5 and added my usual explanation on this topic, with credits to your answer and explanation why the OP's code is unacceptable in general.
—SA
Rate this:
Please Sign up or sign in to vote.

Solution 2

First of all, this is unacceptably bad code. You are relying on "magic words", immediate string constants (which are themselves bad). This is one of the worst anti-patterns:
http://en.wikipedia.org/wiki/Anti-pattern#Programming[^].

Besides, you did not show where the exception with the message "Object reference not set to an instance of an object" is thrown. Please see Solution 1 where at least one of such bugs is explained.

Not to worry. This is one of the very easiest cases to detect and fix. It simply means that some member/variable of some reference type is dereferenced by using and of its instance (non-static) members, which requires this member/variable to be non-null, but in fact it appears to be null. Simply execute it under debugger, it will stop the execution where the exception is thrown. Put a break point on that line, restart the application and come to this point again. Evaluate all references involved in next line and see which one is null while it needs to be not null. After you figure this out, fix the code: either make sure the member/variable is properly initialized to a non-null reference, or check it for null and, in case of null, do something else.

Please see also: want to display next record on button click. but got an error in if condition of next record function "object reference not set to an instance of an object"[^].

Sometimes, you cannot do it under debugger, by one or another reason. One really nasty case is when the problem is only manifested if software is built when debug information is not available. In this case, you have to use the harder way. First, you need to make sure that you never block propagation of exceptions by handling them silently (this is a crime of developers against themselves, yet very usual). The you need to catch absolutely all exceptions on the very top stack frame of each thread. You can do it if you handle the exceptions of the type System.Exception. In the handler, you need to log all the exception information, especially the System.Exception.StackTrace:
http://msdn.microsoft.com/en-us/library/system.exception.aspx[^],
http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx[^].

The stack trace is just a string showing the full path of exception propagation from the throw statement to the handler. By reading it, you can always find ends. For logging, it's the best (in most cases) to use the class System.Diagnostics.EventLog:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx[^].

Good luck,
—SA
   
Comments
Chris_Burns 25-Feb-14 17:11pm
   
I respect that you have a good understanding of programming, but you have to understand, that im a university student, so I've been taught to do things this way. But ive found what part of the code is null, but i cannot get around it.
Sergey Alexandrovich Kryukov 25-Feb-14 17:25pm
   
No ifs, not buts. This is one of the most elementary skills you need to have. You cannot ask for help every time you do this very common bug, which will be especially frequent while you are not very experienced. And I'm helping you to get around such things in general. I have no do you mean by " taught to do things this way". You cannot do it the way which generates bugs.

So, this is not me who misaddress this post, but you who are not accepting it. Read again and think about it.

So, where is you "but"?

—SA
CHill60 26-Feb-14 5:24am
   
Good advice. +5
   
Thank you.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100