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
  • 157,405
  • 24
  • 229
  • 388
mTuran
  • 2,087
  • 4
  • 31
  • 56

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.

Tim Cooper
  • 144,163
  • 35
  • 302
  • 261
Jason Evans
  • 28,042
  • 13
  • 88
  • 145
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
  • 157,405
  • 24
  • 229
  • 388