0
protected void btnSaveSite_Click(object sender, EventArgs e)
{          
      if (ListSelectedCar.Items.Count > 0)
      {
          listSelectedCar.SelectedIndex = 0;
      }

     addNewInventory  addNewInventoryObject = new addNewInventory();
     DataTable dt = addNewInventory.Update_Inventory( id, listSelectedCar.SelectedItem.Text) 

I have two List Boxes ,one of them(ListBox1) List all the available cars and other List box (ListBox2) holds the Car that Customer Selects.If List box 2 holds value there is no problem but as I try to save the Inventory without value in ListBox2 I get Null Referance error .enter image description here

VDWWD
  • 32,238
  • 19
  • 56
  • 70
  • 4
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – VDWWD May 01 '18 at 20:19

2 Answers2

0

The last line tries to get the selected item from box 2 and get the "text" You need to have logic to handle the selected car box "SelectedItem" being null.

You could use a null coelece by doing "SelectedItem?.Text"

BlythMeister
  • 308
  • 1
  • 12
0

A couple of choices here...

Your error message is stating that one (or more) of the objects you're working with is null. You need to identify exactly which one.

Then...

The easiest, but least robust, is to do null checks on the handful of objects you're working with, before trying to do anything with them.

The second, would be to add some client side handling (via javascript, jquery, whatever) to ensure a car is selected before allowing the Save button to trigger your SaveSite action. You can also deliver a popup stating that selecting a car is required.

Your logic is also a little fuzzy. If the item count is not greater than zero, you still try to perform the datatable update. This should probably be INSIDE your IF statement.

user7396598
  • 1,090
  • 7
  • 5