Click here to Skip to main content
14,643,812 members
Rate this:
Please Sign up or sign in to vote.
I'll be brief, I'm making a simple C# desktop application for grocery store. And here, in my problem, The scenario is that:
if the user mentions the quantity that is less than the quantity in the stock, the application performs computations; and if user asks for the quantity that is more than the quantity in the current stock, so the program notifies the user that this is the case and do u still want to continue? if Yes: application performs same computations; and if NO, the application don't performs and clears the textboxes.

all of the scenario works fine except the YES block. if says System.NullReferenceException: Object reference not set to an instance of an object. And refers to the Line: 708. (I have pasted the code below). This line is exact same copy as in the IF block. But it works fine there; not here. I wonder why.




if (data.Rows.Count > 0)
                       {
                           quantity = Convert.ToInt32(data.Rows[0]["item_stock_qty"]);
                       }

                       if (quantity>=Convert.ToInt32(txtBoxQuantity.Text))
                       {
                           AddDataToGridView1((++srNo).ToString(), comboBoxItems.SelectedItem.ToString(),
                               txtBoxUnitPrice.Text.ToString(), txtBoxDiscountPerItem.Text.ToString(),
                               txtBoxQuantity.Text.ToString(), txtBoxSubTotal.Text.ToString(),
                               txtBoxTax.Text.ToString(), txtBoxTotalCost.Text.ToString());
                           ResetControls();
                           CalculateFinalCost();
                       }
                       else
                       {
                           DialogResult dialogResult= MessageBox.Show("The remaining stock of this item is "+quantity+
                               " item/s. Do you still want to Continue?", "Low Stock", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                           if(dialogResult== DialogResult.Yes)
                           {//below is line 708
                               AddDataToGridView1((++srNo).ToString(), comboBoxItems.SelectedItem.ToString(),
                                   txtBoxUnitPrice.Text.ToString(), txtBoxDiscountPerItem.Text.ToString(),
                                   txtBoxQuantity.Text.ToString(), txtBoxSubTotal.Text.ToString(),
                                   txtBoxTax.Text.ToString(), txtBoxTotalCost.Text.ToString());
                               ResetControls();
                               CalculateFinalCost();
                           }
                           else if(dialogResult== DialogResult.No)
                           {
                               ResetControls();
                           }
                           else { }
                       }

                   }
                   catch(Exception ex)
                   {
                       MessageBox.Show(ex.ToString());
                   }


What I have tried:

I have been trying to solve this problem sleeplessly but haven't been able to do so. please help. Thank you
Posted
Updated 9-Feb-20 2:18am
Rate this:
Please Sign up or sign in to vote.

Solution 4

If ya haven't figured it out already, hopefully this will get ya sorted.
You should be able to read the Text Property of the Combobox if an item is selected. The SelectedItem property only returns an object of the inner Collection. So, instead I recommend doing something more like this
comboBoxItems.Items[comboBoxItems.SelectedIndex].ToString()

or
comboBoxItems.Text

either way you will need to make sure an item is selected or the first will return a null reference exception and the second would return an empty string or whatever is typed in the box.

btw: I agree with Dave 100%. Text property is a string value. Calling the ToString() function on a string value is never needed and kind of sloppy. Cheers!
   
Comments
Member 14726765 9-Feb-20 22:13pm
   
Thankyou!!! That worked for me. I saved the index of the selected item first in a separate variable using comboBoxItem.SelectedIndex. and then used that variable in the YES block. and it worked!! :) Thanks a lot
Rate this:
Please Sign up or sign in to vote.

Solution 3

Most likely there is no selected item in your combobox - see ComboBox.SelectedItem Property (System.Windows.Forms) | Microsoft Docs[^].
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
   
Comments
Member 14726765 9-Feb-20 5:27am
   
Thankyou for your well explanation :) and i got the point what you said. I did the debugging procedures and found where the problem is happening. What its saying is that, in the YES block: the combobox.selecteditem is appearing null, this is the reason. But the strange thing is, this same code that is in the YES block, it is also in the previous case i.e. the IF block. There is not that problem, how come the combobox.selecteditem is not null there; and it is null just here, when the distance is just a block away. I'm not getting how to resolve this because the both blocks have the same instructions from the background; the first one is working fine, whereas the latter isn't.
Rate this:
Please Sign up or sign in to vote.

Solution 1

First, a pet peev of mine. Why are you calling .ToString() on textbox.Text properties? IT'S ALREADY A STRING!! That's what a Text property returns!

A NullReferenceException occurs because your code is making assumptions about things working or returning data when it doesn't. A variable contains nothing, or is null. You cannot call methods or get/set properties on objects that don't exists, or are null.

NullReferenceExceptions are among the easiest to figure out and near impossible for anyone to tell you what's wrong. The reason for that is we can't run your code with your data, so it's impossible to anyone to run the code to find the problem for you.

Run the code under the debugger and replicate the problem. When the debugger stops and points you to the line of code that threw the exception, start hovering the mouse over variables in the line to find out which one is null. Then you have to go backwards in the code to figure out why it's null.
   
Comments
Member 14726765 9-Feb-20 2:46am
   
I ran the debugger and did as you advised, and found out that the combobox1.selecteditem.get returned null.
I don't know why its null or how do i fix it because this item is currently selected; so how can it be null. all of the other calculations are based on this combobox's selected item.
OriginalGriff 9-Feb-20 5:36am
   
Given that you don't show us that code, we can't tell! :laugh:

But I'd guess that the different code blocks get executed at different times: one time the method is called when it's null, and one time when it isn't. But as I say, we can't tell from here!
Member 14726765 9-Feb-20 8:40am
   
May i share the code of this whole form in comment?
Dave Kreskowiak 9-Feb-20 10:12am
   
It's null probably because there isn't an item selected in the ComboBox. Like everything else, check to see if SelectedItem is null before you try to use it.

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




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