1

I cannot figure out why I am getting this error. I am setting an instance to the object I am trying to create. Any help would be really appreciated. I will post my form code and then the class code below that. The application runs fine, it just gives me that null reference error when I click on btnAdd.

public partial class frmProperties : Form
{
    Agent curAgent;
    PropertyCollection pc;
    int currRecord;

    public frmProperties()
    {
        InitializeComponent();
    }

    public frmProperties(Agent ac, PropertyCollection pcPassed)
    {
        InitializeComponent();
        curAgent = ac;
        pc = pcPassed;
    }

    //check if there is a property in the list
    private void frmProperties_Load(object sender, EventArgs e)
    {
        if (curAgent.AgentPropertyList.Count > 0)
            ShowAll();
    }

    private void btnNext_Click(object sender, EventArgs e)
    {
        if (currRecord < curAgent.AgentPropertyList.Count - 1)
        {
            currRecord++;
            ShowAll();
        }
        else MessageBox.Show("No more properties to view");
    }

    void ShowAll()
    {

        txtId.Text = curAgent.AgentPropertyList[currRecord].ToString();
        Property p = pc.FindProperty(curAgent.AgentPropertyList[currRecord]);
    }

    private void btnShowPrev_Click(object sender, EventArgs e)
    {
        if (currRecord > 0)
        {
            currRecord--;
            ShowAll();
        }
        else MessageBox.Show("No more properties to view");
    }

    private void btnAdd_Click(object sender, EventArgs e)
    {
        pc.AddProperty(Convert.ToInt32(txtId.Text), txtAddress.Text, Convert.ToInt32(txtBedrooms.Text), txtType.Text, Convert.ToInt32(txtSqFt.Text), Convert.ToDouble(txtPrice.Text), txtAgent.Text);
    }

    private void btnExit_Click(object sender, EventArgs e)
    {
        this.Close();
    }     
}

Here is the code to the class that the add function was created in:

public class PropertyCollection
{
    // list of properties
    List<Property> propertyList = new List<Property>();

    public List<Property> PropertyList
    {
        get { return propertyList; }
        set { propertyList = value; }
    }

    public void AddProperty(int id, string address, int bedrooms, string type, int sqft, double price,string agent)
    {
        Property p = new Property(id,address,bedrooms,type,sqft,price,agent);
        propertyList.Add(p);
    }

    public void RemoveProperty(int id)
    {
        Property rem = new Property(id);
       propertyList.Remove(rem);
    }

    //loop through and find equivalent
    public Property FindProperty(int id)
    {
        Property find = new Property(id);
        for (int i = 0; i < propertyList.Count; i++)
            if (propertyList[i].Equals(find))
                return propertyList[i];
        return null;
    }

    //Count property and INDEXER
    public int Count
    {
        get { return propertyList.Count; }
    }

    public Property this[int i]
    {
        get { return propertyList[i]; }
        set { propertyList[i] = value; }
    }
}
MAV
  • 7,260
  • 4
  • 30
  • 47
Sw33tH2O
  • 33
  • 1
  • 1
  • 6
  • you have two constructors, one empty and one with args, have the empty call the args one. then check if pcPassed is null and if so intitialize a new instance of it. – Sorceri Dec 09 '13 at 23:43
  • 6
    So when you placed a breakpoint on the line that's breaking and you inspected the variables, which one was null? – Conrad Frix Dec 09 '13 at 23:43
  • `pc` isn't always initialised for the reasons Sorceri outlined. – Chris Dec 09 '13 at 23:45
  • throw away accounts are annoying, question poster should have accepted or written and accepted an answer – stackuser83 Dec 18 '13 at 18:55
  • set 'break on exception thrown' in the debugger and then you will see where the error happens and can work out why – pm100 Apr 08 '15 at 00:56

2 Answers2

0

Your default constructor isn't initialising pc; You could change it to the following:

public frmProperties()
{
    InitializeComponent();
    pc = new PropertyCollection(/* any params here */);

}
damienc88
  • 1,957
  • 19
  • 34
0

I am posting this as I am more or less peaved at the 5 upticks to check the breakpoint as it showed the commentor did not read the question.

Posted stated receiving System.NullReferenceException {“Object reference not set to an instance of an object.”} when clicking on the btnAdd_Click method

So we look at this method and it shows we are only accessing 1 variable named pc. The error tells us we have an object that has not been initialized. So we look to see if the variable is define, sure is. now we look to see whereit is initialized so lets look at the constructors.

//this constructor does not initialize any variables, just the form
public frmProperties()
{
    InitializeComponent();
}

//this constructor initializes the variables but does not check for null
public frmProperties(Agent ac, PropertyCollection pcPassed)
{
    InitializeComponent();
    curAgent = ac;
    pc = pcPassed;
}

so we have two issues that could result in the proceeding exception.
1) the default constructor is being called therefor pc is never initialized 2) the second constructor is being called and pcPassed has a value of null.

so to fix this we could remove the first constructor requiring that the arguments be passed in in order to start the form then we just need to check for null on the variables. Or leave the default constructor and call the correct one passing in default values or nulls, I suggest nulls that way all processing is done in the constructor with args. So the fix would be

//default constructor calling the correct constructor with params.
public frmProperties() :this(null,null) { }


public frmProperties(Agent ac, PropertyCollection pcPassed)
{
    InitializeComponent();
    if(ac != null) //check for null values
        curAgent = ac;
    else
        curAgent = new Agent();
    if(pcPassed != null)//check for null values
        pc= pcPassed;
    else
        pc = new PropertyCollection();  

}

so in short you dont need the breakpoint as you already know that the object was not initialized as that is what the exception was telling you.

Sorceri
  • 7,870
  • 1
  • 29
  • 38