none
Why Object reference not set to an instance of an object. RRS feed

  • Question

  • Hi,

    Why I am getting:

    System.NullReferenceException: Object reference not set to an instance of an object.

    For ViewModel like this:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Zeera
    {
        public class Notifier : INotifyPropertyChanged
        {
            public Notifier()
            {
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            public void OnPropertyChanged(string name)
            {
                if (this.PropertyChanged != null)
                    this.PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
    
            public bool editVisible = true;
            public bool IsEditVisible
            {
                get { return editVisible; }
                set
                {
                    editVisible = value;
                    OnPropertyChanged("IsEditVisible");
                }
            }
    
            public bool deleteVisible = true;
            public bool IsDeleteVisible
            {
                get { return deleteVisible; }
                set
                {
                    deleteVisible = value;
                    OnPropertyChanged("IsDeleteVisible");
                }
            }
        }
    }


    and from my code I am setting the IsDeleteVisible like this:

    var delete_button = (e.ItemData as Notifier);
    
    
    if ((e.ItemData as LocationData).is_readonly == true)
    
    {    
    
         delete_button.IsDeleteVisible = false;
    
    }
    
    else
    
    {    
    
         delete_button.IsDeleteVisible = true;
    
    }
    
    
    
    


    Kindly help..

    Thanks,

    Jassim


    Friday, April 19, 2019 6:43 PM

All replies

  • where are you getting the error?   Did you not create an instance of the ViewModel class before using it 
    Saturday, April 20, 2019 11:57 AM
  • Yes I did tried below as well but same error:

    Notifier notifier = new Notifier();
    
    notifier = (e.ItemData as Notifier);
    
    if ((e.ItemData as LocationData).is_readonly == true)
    {
        notifier.IsDeleteVisible = false;
    }
    else
    {
        notifier.IsDeleteVisible = true;
    }
    

    the error is showing on this line:

    notifier.IsDeleteVisible = false;

    Saturday, April 20, 2019 4:23 PM
  • You are trying to cast e.ItemData to both a Notifier and LocationData which is not working.

    notifier = (e.ItemData as Notifier);
    
    if ((e.ItemData as LocationData).is_readonly == true)

    The as will cast the object if possible otherwise it will return a null.  I am guessing the object reference error is because the e.ItemData cant be cast to Notifier so it is a null.

    Sunday, April 21, 2019 1:51 AM