Honestly… I haven’t got a clue what I’m doing wrong… I get the error
Object reference not set to an instance of an object
The code is shown below and I have the marked the error using the /////.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MonuEventPlanning
{
public partial class Form1 : Form
{
DinnerFun dinnerFun;
public Form1()
{
InitializeComponent();
DinnerFun dinnerFun = new DinnerFun { PeepQty = (int)nudPeepQty.Value };
}
public void btnCalc_Click(object sender, EventArgs e)
{
dinnerFun.CalcDrinks(cbxHealthy.Checked); ///////PROBLEM HERE////////////////
dinnerFun.CalcDecorations(cbxFancy.Checked);
DisplayCost();
}
public void DisplayCost()
{
tbxDisplayCost.Text = dinnerFun.CalcTotalCost(cbxHealthy.Checked).ToString("c");
}
}
}
Here is my other page of code with this practice project I am doing:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MonuEventPlanning
{
public partial class Form1 : Form
{
DinnerFun dinnerFun;
public Form1()
{
InitializeComponent();
DinnerFun dinnerFun = new DinnerFun { PeepQty = (int)nudPeepQty.Value }; //This object is instantiated again? Or is this the same dinnerFun from above?
}
public void btnCalc_Click(object sender, EventArgs e)
{
dinnerFun.CalcDrinks(cbxHealthy.Checked);
dinnerFun.CalcDecorations(cbxFancy.Checked);
DisplayCost();
}
public void DisplayCost()
{
tbxDisplayCost.Text = dinnerFun.CalcTotalCost(cbxHealthy.Checked).ToString("c");
}
}
}
Some help would be appreciated.
In the constructor you are not putting the
DinnerFunobject in thedinnerFunmember that you have declared in the form. You are creating another local variable with the same name inside the constructor. When you try to use the member later on, it will still be null.Just remove the variable declaration from the assignment: