C# Help!

Associate
Joined
22 May 2011
Posts
1,445
Location
Edinburgh
Hey all,

I'm having trouble with a piece of C#. I have code which as far as I am aware works correctly in distinguishing whether an object is of the base class, or one of its two child classes. However in another part of the program the conditions of class are never being met.. I have this:

Code:
foreach (Booking c in myCamp.camp)
            {
                string line = "Booking: " + c.week+" " + c.name + " " + c.address + " " + c.children;
                if (c.GetType() == typeof(Activity))
                    {
                        Activity a = (Activity)c;
                        line = line + a.kind + "dave " + a.U16;
                    }

                if (c.GetType() == typeof(Cruise))
                {
                    Cruise b = (Cruise)c;
                    line = line + b.bora;
                }
                lstBookings.Items.Add(line);
            }

Thing is neither of the ifs are ever satisfied and all instansiations come out as objects of the base class. Help!
 
I've added the code as posted above and it runs as it should, however it still is doing the same thing. I think the conditions on my IF statement are never being met :(

Code:
            if (theBooking == null) //If new bookingr...
            {
                if (ActivityButton.Checked == true)
                {
                    theBooking = new Activity(txtWeek.Text, txtName.Text, txtAddress.Text, Convert.ToInt32(txtChildren.Text), label6.Text, comboBox1.Text,Convert.ToBoolean(comboBox3.SelectedItem));
                }

                if (CruiseButton.Checked == true)
                {
                    theBooking = new Cruise(txtWeek.Text, txtName.Text, txtAddress.Text, Convert.ToInt32(txtChildren.Text), label7.Text, comboBox2.Text);
                }

                theBooking = new Booking(txtWeek.Text, txtName.Text, txtAddress.Text, Convert.ToInt32(txtChildren.Text),label8.Text);

            }
            else
            {   //if editing an existing booking
                theBooking.name = txtName.Text;
                theBooking.week = txtWeek.Text;
                theBooking.address = txtAddress.Text;
                theBooking.children = Convert.ToInt32(txtChildren.Text);
                
            }
 
I've been ploughing on and I've hit a snag, a Null Handling Exception.

Basically I have to add a Customer class, it doesn't need to link to anything, but it needs its own box to store the data in, very much a mirror copy of the stuff I already have, but when I run the method for updating the list it throws the above mentioned error :@

This is the class:

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SD2coursework
{
    public class Customer
    {
        private string theName;
        private string theAddress;
        private int theID;

        public Customer(string aName, string anAddress, int anID)
        {
            theName = aName;
            theAddress = anAddress;
            theID = anID;
        }
    

    public string Name
    {
      get
      {
        return theName;
      }
      set
      {
          theName = value;
      }
    }

    public string Address
    {
      get 
      {
          return theAddress;  
      }
      set 
      {
          theAddress = value;
      }
    }

    public int ID
    {
        get 
        {
          return theID;
        }
        set 
        {
          theID = value;
        }
    }

    public virtual string GetLine()
    {
        return string.Format("Name: {0}, Address: {1}, ID Number: {2} ", Name, Address, ID);
    }
    
    }
}

This is the customer storing method:

Code:
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 SD2coursework
{
    public partial class FrmCustBooking : Form
    {

        private Customer theCust = null;

        public Customer Cust
        {
            get 
            {
                return theCust;
            }

            set 
            {
                theCust = value;
                textBox1.Text = theCust.Name;
                textBox2.Text = theCust.Address;
                textBox3.Text = Convert.ToString(theCust.ID);
            }
        
        }


        public FrmCustBooking()
        {
            InitializeComponent();
        }

       
        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    
        private void FrmCustBooking_FormClosed(object sender, FormClosedEventArgs e)
        {
            if(theCust == null)
            {
                theCust = new Customer(textBox1.Text, textBox2.Text, Convert.ToInt32(textBox3.Text));
            }

            else
            {
                theCust.Name = textBox1.Text;
                theCust.Address = textBox2.Text;
                theCust.ID = Convert.ToInt32(textBox3.Text);
            }
        }
    
    
    
    
    }
}

And the list update part

Code:
        private void updateBookingList()
        {   //Used to update the camp displayed on the form
            lstBookings.Items.Clear();
            foreach (var Booking in myCamp.camp)
            {
                var line = Booking.GetLine();
                lstBookings.Items.Add(line);
            }

            lstCustomers.Items.Clear();
            foreach (var Customer in cust.log)
            {
                var line = Customer.GetLine();
                lstCustomers.Items.Add(line);
            }
        }

Anyone see whats wrong? :'(
 
The getter for Customer Cust is trying to return a null object:
Code:
        ...
        private Customer theCust = null;

        public Customer Cust
        {
            get 
            {
                return theCust;
            }
        ...
        }
You could add a if(theCust== null) check and instantiate it just before returning theCust?

If I add that I no longer get the Null exception, however I do get stack overflow :/
 
I am a total C# and debugging noob. Unfortunately my course and teachers were more interested in teaching us OO fundamentals instead of how to actually use VS and the debugging interface and general good practice.

We we just get dumped with some sample code and some briefs. I won't pretend for a single moment that I am a good programmer, unfortunately though I need to learn this :S
 
This is the details of the error it is giving.

With the breakpoint at the line where the null error is given
Code:
var line = Customer.Getline();

The line variable is null, and the Customer class is also null. So would I be right in saying that even-though I believe all the needed code is there, I am never instantiating an object of the customer class?
Code:
System.NullReferenceException was unhandled
  Message=Object reference not set to an instance of an object.
  Source=SD2coursework
  StackTrace:
       at SD2coursework.FrmHolidayCamp.updateCustomerList() in G:\Assessment\WindowsFormsApplication1\FrmCampBookings.cs:line 45
       at SD2coursework.FrmHolidayCamp.button1_Click(Object sender, EventArgs e) in G:\Assessment\WindowsFormsApplication1\FrmCampBookings.cs:line 99
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at SD2coursework.Program.Main() in G:\Assessment\WindowsFormsApplication1\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:
 
HolidayCamp isn't a form its a class:

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SD2coursework
{
    class HolidayCamp
    {
        /*
         * This class is used to hold a list of Holiday objects that make up the holiday camp:
         * The Holiday objects may be added through the addToCamp() method.
         * The car objects may be deleted tgrough the removeFromCamp() method 
         * Use the camp property to access the list of Holiday objects
         */ 

        private List<Booking> theCamp = new List<Booking>(); //The list of car objects being stored
        private List<Customer> custLog = new List<Customer>();
        public List<Booking> camp 
            /* The camp property. Note that you can only read it
             * use the addToCamp and removeFromCamp to update it
             */
        {
            get
            {
                return theCamp;
            }
        }

        public List<Customer> log
        {
            get
            {
                return custLog;
            }
        }

        public void removeFromCamp(Booking aHoliday)
            //Remove booking from camp
        {
            theCamp.Remove(aHoliday);
        }

        public void addbookToCamp(Booking aHoliday)
            //Add booking to camp
        {
            theCamp.Add(aHoliday);
        }

        public void removeCust(Customer aCust)
        {
            custLog.Remove(aCust);
        }

        public void addCust(Customer aCust)
        {
            custLog.Add(aCust);
        }
    }
}

And this is the Camp booking class:

Code:
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 SD2coursework
{
    public partial class FrmHolidayCamp : Form
    /*
     * This is the main form for the booking system.
     * It allows the adding to new bookings to the system, and displaying them 
     * 
     */
    {
        private HolidayCamp myCamp = new HolidayCamp();
        //Holiday object used to store bookings

        private HolidayCamp cust = new HolidayCamp();

        public FrmHolidayCamp()
        {
            //Default constructor
            InitializeComponent();
        }


        private void updateBookingList()
        {   //Used to update the camp displayed on the form
            lstBookings.Items.Clear();
            foreach (var Booking in myCamp.camp)
            {
                var line = Booking.GetLine();
                lstBookings.Items.Add(line);
            }
        }
       private void updateCustomerList()
       {
            lstCustomers.Items.Clear();
            foreach (var Customer in cust.log)
            {
                var line = Customer.Getline();
                lstCustomers.Items.Add(line);
            }
        }

        private void btnAddBooking_Click(object sender, EventArgs e)
        {
            //Add a new Booking
            FrmBooking bookingGui = new FrmBooking();   //Form used to add new Holiday
            bookingGui.ShowDialog();
            Booking myHoliday = bookingGui.booking;         //Get new holiday from form
            myCamp.addbookToCamp(myHoliday);               //Add to camp list
            updateBookingList();                      //Uodate camp list
        }

        private void lstBookings_SelectedIndexChanged(object sender, EventArgs e)
        {
            /*
             * This method is used to control the list box
             * It is called when a row is selected by the user, it then displays frmBooking
             * with the booking details
             */
            if (lstBookings.SelectedIndex > -1)
            {
                int index = lstBookings.SelectedIndex;
                Booking myBooking = myCamp.camp.ElementAt(index);
                FrmBooking bookingGui = new FrmBooking();
                bookingGui.booking = myBooking;
                bookingGui.ShowDialog();
                updateBookingList();

            }
        }

        private void lstCustomers_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstCustomers.SelectedIndex > -1)
            {
                int index = lstCustomers.SelectedIndex;
                Customer myCust = cust.log.ElementAt(index);
                FrmCustBooking CustGui = new FrmCustBooking();
                CustGui.Cust = myCust;
                CustGui.ShowDialog();
                updateCustomerList();
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            FrmCustBooking CustGui = new FrmCustBooking();   //Form used to add new Holiday
            CustGui.ShowDialog();
            Customer myCust = CustGui.Cust;         //Get new holiday from form
            cust.addCust(myCust);               //Add to camp list
            updateCustomerList(); 
        }
    }
}
 
An ENORMOUS thanks to Pho for solving my problem in like a minute, if that.

I mailed him the code today to look over and he got it straight away.

I hadn't associated (if that's the right word) my whole FrmCustBooking_Closed thing with actually closing the form, so it was never being ran, so Customers were never being instantiated and nulls were always being thrown.

My apologies for wasting all your time with my ludicrous problems, I certainly need to look into debugging best practice. I promise next time I post on here I'll be better :D

Thanks to all of you, and especially Pho, you guys are awesome :)
 
Back
Top Bottom