0

I am trying to code simple membership class. First class name is Customer and it has others classes like Silver_Customer, Gold_Customer which are inherited from Customer class.

I use these classes in my simple windows application:

    public Customer customer;
    public Form_MURAT_TURAN()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        Product p1 = new Product("Blouse", 152.80);
        Product p2 = new Product("T-Shirt", 50.25);
        .....
        lbProducts.Items.Add(p1);
        lbProducts.Items.Add(p2);
        .....
    }

    private void btnCustomer_Click(object sender, EventArgs e)
    {
        Customer customer = new Standard_Customer(txtName.Text, txtSurname.Text, 0);
        customer.Name = "Mark 1";
        customer.TotalAmount = 5;
        gbCustomer.Enabled = false;
        gbProduct.Enabled = true;

        set_info(customer.customerType(), customer.Name + " " + customer.Surname, customer.TotalAmount);
    }

    private void btnAddToBasket_Click(object sender, EventArgs e)
    {
        customer.Name = "Mark 2";
    }

Everything works fine except btnAddToBasket_Click method. customer.Name = "Mark 2"; line give me NullReferenceException error but customer.Name = "Mark 1" line works.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
mTuran
  • 1,846
  • 4
  • 32
  • 58

2 Answers2

2

Why don't you try:

private void btnCustomer_Click(object sender, EventArgs e)
{
        this.customer = new Standard_Customer(txtName.Text, txtSurname.Text, 0);
        customer.Name = "Mark 1";
        customer.TotalAmount = 5;
        gbCustomer.Enabled = false;
        gbProduct.Enabled = true;

        set_info(customer.customerType(), customer.Name + " " + customer.Surname, customer.TotalAmount);
    }

Try using this.customer when you create a new customer.

Jason Evans
  • 28,906
  • 14
  • 90
  • 154
1

In btnCustomer_Click, you are not setting your global customer object. You are setting a local version of it. Change your code as follows:

private void btnCustomer_Click(object sender, EventArgs e)
{
    customer = new Standard_Customer(txtName.Text, txtSurname.Text, 0);
John Saunders
  • 160,644
  • 26
  • 247
  • 397