Displaying Contents of List in TextBox - Windows Form Application

  • (3 Pages)
  • +
  • 1
  • 2
  • 3

31 Replies - 12888 Views - Last Post: 22 May 2011 - 11:20 AM Rate Topic: -----

#1 John316  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 03-May 11

Displaying Contents of List in TextBox - Windows Form Application

Posted 17 May 2011 - 03:09 AM

Hello,
I have created a menu driven windows form application where the user can add customers to a list. After adding the customers details i need the contents of the list(The customers details) to be displayed in a text box on the main menu.

The main menu has a button prompting the user to (Add New Customers), after clickin this they are asked to enter the customer details then click (Add Customer) button. After returning to the main menu there is another button asking(Show Customer Details) upon clicking this i need the contents of the customers list to be shown in the textbox.

I am unsure what code i need to first: Make sure the details are stored in the list, and second: How to display this list.
I have tried code for showing customers in (displayCustomersButton_Click) and ShowCustomers() but i believe this is totally wroing!

I have provided code below for my customer class, and my customerStore class. And the two forms.
Any help would be great.
Thank You
  class Customer
    {
        // Attributes
        string _fullName;
        string _address;
        string _telephoneNumber;
        string _emailAddress;

        // Constructor
      public Customer(string fullname, string address, string telephoneNumber, string emailAddress)
        {
            _fullName = fullname;
            _address = address;
            _telephoneNumber = telephoneNumber;
            _emailAddress = emailAddress;
        }
        // Properties
        public string FullName
        {
            get
            {
                return _fullName;
            }
        }

        public string Address
        {
            get
            {
                return _address;
            }
        }

        public string TelephoneNumber
        {
            get
            {
                return _telephoneNumber;
            }
        }

        public string EmailAddress
        {
            get
            {
                return _emailAddress;
            }       }
    }



class CustomerStore
    {
         //Attributes

        private List<Customer> _customers;

        // Constructor

        public CustomerStore()
        {
            _customers = new List<Customer>();        // Create list of Customers
        }

        // Methods

        public void AddCustomer(Customer customer)
        {
            _customers.Add(customer);                // Enables customers to be added to list
        }

        public void ShowCustomers()
        {
            foreach (Customer customer in _customers)
            {
                Console.WriteLine(customer.FullName);
                Console.WriteLine(customer.Address);
                Console.WriteLine(customer.TelephoneNumber);
                Console.WriteLine(customer.EmailAddress);
            }
        }
    }


public partial class AddCustomer : Form
    {
        public AddCustomer()
        {
            InitializeComponent();
        }

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

        private void addCustomerButton_Click(object sender, EventArgs e)
        {
           
        }
    }


 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {

        }

        private void addVehicleButton_Click(object sender, EventArgs e)
        {
            AddVehicle nextForm = new AddVehicle();

            nextForm.Show();      
        }

        private void displayCustomersButton_Click(object sender, EventArgs e)
        {
            CustomerStore customerStore;
            customerStore = new CustomerStore();
            customerStore.ShowCustomers();
            displayTextBox.Show();
    
        }

        private void addNewCustomerButton_Click(object sender, EventArgs e)
        {
            AddCustomer nextForm = new AddCustomer();
            nextForm.Show();
            
        }
    }



Is This A Good Question/Topic? 0
  • +

Replies To: Displaying Contents of List in TextBox - Windows Form Application

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6092
  • View blog
  • Posts: 23,613
  • Joined: 23-August 08

Re: Displaying Contents of List in TextBox - Windows Form Application

Posted 17 May 2011 - 03:20 AM

private void displayCustomersButton_Click(object sender, EventArgs e)
       {
           CustomerStore customerStore;
           customerStore = new CustomerStore();
           customerStore.ShowCustomers();
           displayTextBox.Show();
   
       }


Yes, it's wrong because you've created an entirely new CustomerStore with no customers. You want to show the customers you've ALREADY STORED! Where (in what variable) did you store your customers?
Was This Post Helpful? 0
  • +
  • -

#3 John316  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 03-May 11

Re: Displaying Contents of List in TextBox - Windows Form Application

Posted 17 May 2011 - 03:26 AM

Thanks for your quick reply.

I created the CustomerStore class to create the list of customers but i havent created any variables. Should i be creating a "generic customer" to do this?? Where would i need this variable to be?

Would this not store the customers??

 public void AddCustomer(Customer customer)
        {
            _customers.Add(customer);                // Enables customers to be added to list
        }


Was This Post Helpful? 0
  • +
  • -

#4 Servatis  Icon User is offline

  • D.I.C Regular

Reputation: 48
  • View blog
  • Posts: 394
  • Joined: 30-March 09

Re: Displaying Contents of List in TextBox - Windows Form Application

Posted 17 May 2011 - 03:29 AM

I looks like you don't really understand what you are trying to do here.
  • You cant use Console.WriteLine in a forms application.
  • You need to create a CustomerStore object at the start of the application and keep using that same object.
  • You need to actually save the customer in your AddCustomer form


I'm sure a nice DICer will come along with a helpful list of links for you to visit.
Was This Post Helpful? 1
  • +
  • -

#5 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6092
  • View blog
  • Posts: 23,613
  • Joined: 23-August 08

Re: Displaying Contents of List in TextBox - Windows Form Application

Posted 17 May 2011 - 03:44 AM

Quote

I created the CustomerStore class to create the list of customers but i havent created any variables.


What's this then?

_customers = new List<Customer>();        // Create list of Customers


Listen, you should have a pretty solid understanding of classes BEFORE you jump into UI programming. It does not appear that you do.
Was This Post Helpful? 0
  • +
  • -

#6 John316  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 03-May 11

Re: Displaying Contents of List in TextBox - Windows Form Application

Posted 17 May 2011 - 03:48 AM

I know exactly what i am trying to do, it's being aboe to do it is the problem!

I think i better go at this is stages.
So my first problem is making sure that when the user hits the add customer button the information is stored correctly in the _customers list.
So i need the correct coding to go here:

       private void addCustomerButton_Click(object sender, EventArgs e)
        {
           
        }
    }



And to make sure this code is correct:
Can anyone help on what needs to go in these code blocks in order for the customer details to be stored correctrly to the list??
class CustomerStore
    {
         //Attributes

        private List<Customer> _customers;

        // Constructor

        public CustomerStore()
        {
            _customers = new List<Customer>();        // Create list of Customers
        }

        // Methods

        public void AddCustomer(Customer customer)
        {
            _customers.Add(customer);                // Enables customers to be added to list
        }
    }


Was This Post Helpful? 0
  • +
  • -

#7 John316  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 03-May 11

Re: Displaying Contents of List in TextBox - Windows Form Application

Posted 17 May 2011 - 05:28 AM

Thank you for your critisicm jackofalltrades, but that dosent help me in getting the application to work.

I have made a little progress.
I have scrapped the customerStore class as it was unessecary and created a genericCustomer variable and if i give this variable values e.g (John, 081933337) these display in my customers listbox when i click the show customers button.(the name does but none of the other info as yet!).

The problem i am having is with the enter customer details form.
This form askes the user to enter in texboxes the customer name,address,telephone and email.I want this information to then be stored in a list.
And when i return to the main menu and click(show customer details button) all customers and their details are to be shown in the customers listbox.

How can i get this information stored into the list and then displayed.Any help would be great.
 public partial class Form1 : Form
    {
        private List<Customer> _customers = new List<Customer>();

        public Form1()
        {
            
            InitializeComponent();
           
        }

        private void Main_Load(object sender, EventArgs e)
        {

        }

        private void displayCustomersButton_Click(object sender, EventArgs e)
        {             
            Customer genericCustomer;
            genericCustomer = new Customer("John", "Penrhos", "0143211806", "john.com");
            _customers.Add(genericCustomer);

            customerListBox.DataSource = _customers;
        }

        private void addNewCustomerButton_Click(object sender, EventArgs e)
        {
            AddCustomer nextForm = new AddCustomer();
            nextForm.Show();
            
        }

        private void customerListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }
    }


   private void addCustomerButton_Click(object sender, EventArgs e)
        {            
           
        }


Was This Post Helpful? 0
  • +
  • -

#8 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6092
  • View blog
  • Posts: 23,613
  • Joined: 23-August 08

Re: Displaying Contents of List in TextBox - Windows Form Application

Posted 17 May 2011 - 05:39 AM

You were actually on the right track with the CustomerStore class, you should not scrap it.

Simple way to do this (not necessarily the BEST way):
1. Your application needs to create an instance of the CustomerStore class at the start.
2. Your AddCustomer form should have a Customer member variable which is exposed through a property and is populated when the appropriate form button is clicked.
3. Your application gets the Customer from the AddCustomer form and adds it to the CustomerStore.
4. When you want to display the list of Customers, you use the instance of the CustomerStore variable.

Get it?
Was This Post Helpful? 1
  • +
  • -

#9 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5632
  • View blog
  • Posts: 12,082
  • Joined: 02-June 10

Re: Displaying Contents of List in TextBox - Windows Form Application

Posted 17 May 2011 - 06:04 AM

Critique of your code before going further:
All of your Customer class properties are read-only.
How do you intend to set the customer's name, phone number and so on?

// Properties
string _fullname;
      public string FullName
      {
          get
          {
              return _fullName;
          }
      }



There is no point to having the private field _fullname. It serves no purpose here and only adds to complicate the readability of the code. At least at this point. You might as well just do this
public string Fullname
{
    get; set;
}


I would suggest you use #region markers to surround your different regions of code. You are so close to having really clean readable code, why not go that extra 1 line to be able to close up entire areas with the click of a mouse?

#region Properties
public string Fullname
{
    get; set;
}
public string Phone
{
    get; set;
}
public string Address
{
    get; set;
}
#endregion Properties



If you are going to have fields as the back-end to properties then you don't access the fields directly. You go through the properties. That's the point of them. Here you should be setting the property Customers instead of the field _customers

public CustomerStore()
        {
            _customers = new List<Customer>();        // Create list of Customers
        }



Quote

So i need the correct coding to go here:
private void addCustomerButton_Click(object sender, EventArgs e)
    {
       
    }

here's where you really haven't planned ahead and may have some trouble with more advanced concepts. Maybe you won't. I'm just saying that you seem to be moving a little fast compared to what you've shown us that you understand so far. Before you get upset, here's why I say that: Your addcustomer button is part of a completely different class/form. Being part of a different class it knows nothing about your main form or it's properties such as the Customers list. If the AddCustomerForm doesn't know of the Customers list, or the Customers class even, then it will be hard for it to make a Customer object at all, let alone add it to the collection it can't see. You're going to have to create a new customer object within the AddCustomerForm, then raise an event with that new customer as the event arguments. The main form will have to have subscribed to the NewCustomerEvent. Then when the main form hears the AddCustomerForm raise the NewCustomerEvent, the main form will then take the NewCustomerArgs and add it to the Customers list.

Here's my suggestion to you... We have several good tutorials on how to build an application, how to create custom events, and how to transfer data between separate classes/forms. Stop work on this project. Go work through the tutorials. This will give you a much stronger understanding of what you need to do and give you the coding skills with which to do it. Then come back to this project and re-evaluate where you need to go from here.

The tutorials below walk through making an application including inheritance, custom events and custom controls.
Bulding an application - Part 1
Building an application - Part 2
Quick and easy custom events
Passing values between forms/classes

You may also want to review the chapter on properties in whatever book you are working with as you seem to missed some understanding about them.
Was This Post Helpful? 2
  • +
  • -

#10 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6092
  • View blog
  • Posts: 23,613
  • Joined: 23-August 08

Re: Displaying Contents of List in TextBox - Windows Form Application

Posted 17 May 2011 - 06:09 AM

*
POPULAR

I just whipped up a quick example.

FruitStorage.cs
using System.Collections.Generic;

namespace FruitStand
{
    class FruitStorage
    {
        public FruitStorage()
        {
            Fruits = new List<Fruit>();
        }

        public void AddFruit(Fruit fruit)
        {
            Fruits.Add(fruit);
        }

        public List<Fruit> Fruits { get; private set; }
    }
}



Fruit.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FruitStand
{
    public class Fruit
    {
        public Fruit(string name, int quantity)
        {
            Name = name;
            Quantity = quantity;
        }

        public override string ToString()
        {
            return String.Format("{0}: {1} on hand", Name, Quantity);
        }
        public string Name { get; private set; }
        public int Quantity { get; private set; }
    }
}



AddFruit.Designer.cs
namespace FruitStand
{
    partial class AddFruit
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.fruitName = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.fruitCount = new System.Windows.Forms.NumericUpDown();
            this.okButton = new System.Windows.Forms.Button();
            this.cancelButton = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.fruitCount)).BeginInit();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(12, 23);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(38, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "Name:";
            // 
            // fruitName
            // 
            this.fruitName.Location = new System.Drawing.Point(116, 20);
            this.fruitName.Name = "fruitName";
            this.fruitName.Size = new System.Drawing.Size(221, 20);
            this.fruitName.TabIndex = 1;
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(15, 60);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(95, 13);
            this.label2.TabIndex = 2;
            this.label2.Text = "Quantity On Hand:";
            // 
            // fruitCount
            // 
            this.fruitCount.Location = new System.Drawing.Point(116, 58);
            this.fruitCount.Name = "fruitCount";
            this.fruitCount.Size = new System.Drawing.Size(120, 20);
            this.fruitCount.TabIndex = 3;
            // 
            // okButton
            // 
            this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.okButton.Location = new System.Drawing.Point(228, 124);
            this.okButton.Name = "okButton";
            this.okButton.Size = new System.Drawing.Size(75, 23);
            this.okButton.TabIndex = 4;
            this.okButton.Text = "OK";
            this.okButton.UseVisualStyleBackColor = true;
            this.okButton.Click += new System.EventHandler(this.okButton_Click);
            // 
            // cancelButton
            // 
            this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.cancelButton.Location = new System.Drawing.Point(309, 124);
            this.cancelButton.Name = "cancelButton";
            this.cancelButton.Size = new System.Drawing.Size(75, 23);
            this.cancelButton.TabIndex = 5;
            this.cancelButton.Text = "Cancel";
            this.cancelButton.UseVisualStyleBackColor = true;
            // 
            // AddFruit
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(394, 153);
            this.Controls.Add(this.cancelButton);
            this.Controls.Add(this.okButton);
            this.Controls.Add(this.fruitCount);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.fruitName);
            this.Controls.Add(this.label1);
            this.Name = "AddFruit";
            this.Text = "Add Fruit";
            ((System.ComponentModel.ISupportInitialize)(this.fruitCount)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox fruitName;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.NumericUpDown fruitCount;
        private System.Windows.Forms.Button okButton;
        private System.Windows.Forms.Button cancelButton;
    }
}


AddFruit.cs
using System.Windows.Forms;

namespace FruitStand
{
    public partial class AddFruit : Form
    {
        public AddFruit()
        {
            InitializeComponent();
        }

        private void okButton_Click(object sender, EventArgs e)
        {
            NewFruit = new Fruit(fruitName.Text, (int)fruitCount.Value);
        }

        public Fruit NewFruit { get; private set; }
    }
}


Form1.Designer.cs
namespace FruitStand
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.addFruitButton = new System.Windows.Forms.Button();
            this.getFruitButton = new System.Windows.Forms.Button();
            this.fruitList = new System.Windows.Forms.ListBox();
            this.SuspendLayout();
            // 
            // addFruitButton
            // 
            this.addFruitButton.Location = new System.Drawing.Point(39, 33);
            this.addFruitButton.Name = "addFruitButton";
            this.addFruitButton.Size = new System.Drawing.Size(75, 23);
            this.addFruitButton.TabIndex = 0;
            this.addFruitButton.Text = "Add a Fruit";
            this.addFruitButton.UseVisualStyleBackColor = true;
            this.addFruitButton.Click += new System.EventHandler(this.addFruitButton_Click);
            // 
            // getFruitButton
            // 
            this.getFruitButton.Location = new System.Drawing.Point(39, 71);
            this.getFruitButton.Name = "getFruitButton";
            this.getFruitButton.Size = new System.Drawing.Size(75, 23);
            this.getFruitButton.TabIndex = 1;
            this.getFruitButton.Text = "Get All Fruit";
            this.getFruitButton.UseVisualStyleBackColor = true;
            this.getFruitButton.Click += new System.EventHandler(this.getFruitButton_Click);
            // 
            // fruitList
            // 
            this.fruitList.FormattingEnabled = true;
            this.fruitList.Location = new System.Drawing.Point(149, 33);
            this.fruitList.Name = "fruitList";
            this.fruitList.Size = new System.Drawing.Size(388, 251);
            this.fruitList.TabIndex = 2;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(563, 309);
            this.Controls.Add(this.fruitList);
            this.Controls.Add(this.getFruitButton);
            this.Controls.Add(this.addFruitButton);
            this.Name = "Form1";
            this.Text = "Jack\'s Fruit Stand";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button addFruitButton;
        private System.Windows.Forms.Button getFruitButton;
        private System.Windows.Forms.ListBox fruitList;
    }
}



Form1.cs
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 FruitStand
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void addFruitButton_Click(object sender, EventArgs e)
        {
            AddFruit addFruitForm = new AddFruit();
            if (DialogResult.OK == addFruitForm.ShowDialog())
            {
                fruitStorage.AddFruit(addFruitForm.NewFruit);
            }
        }

        private FruitStorage fruitStorage;

        private void Form1_Load(object sender, EventArgs e)
        {
            fruitStorage = new FruitStorage();
        }

        private void getFruitButton_Click(object sender, EventArgs e)
        {
            fruitList.Items.Clear();
           
            foreach (var fruit in fruitStorage.Fruits)
            {
                fruitList.Items.Add(fruit);
            }
        }
    }
}


Was This Post Helpful? 6
  • +
  • -

#11 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5632
  • View blog
  • Posts: 12,082
  • Joined: 02-June 10

Re: Displaying Contents of List in TextBox - Windows Form Application

Posted 17 May 2011 - 06:23 AM

Nice Jack. That's really going out there to provide an example. I wish I could +1 that more than once; you deserve it.
Was This Post Helpful? 0
  • +
  • -

#12 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6092
  • View blog
  • Posts: 23,613
  • Joined: 23-August 08

Re: Displaying Contents of List in TextBox - Windows Form Application

Posted 17 May 2011 - 06:27 AM

Heh, thanks. I need the practice...I'm out here scrounging for a job, and C# seems to be the hot commodity. :)
Was This Post Helpful? 0
  • +
  • -

#13 John316  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 03-May 11

Re: Displaying Contents of List in TextBox - Windows Form Application

Posted 17 May 2011 - 10:52 AM

Thank you both for your helpful responses, I shall take on board what you have both suggested and advised and have a go at the tutorials linked.
Was This Post Helpful? 0
  • +
  • -

#14 MATTtheSEAHAWK  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 137
  • View blog
  • Posts: 782
  • Joined: 11-September 10

Re: Displaying Contents of List in TextBox - Windows Form Application

Posted 17 May 2011 - 03:01 PM

Also just posting this because it could make adding customers a little bit easier. In Visual Basic you can use the InputBox and in C# you can to. It is almost like a message box except it has a text box for input and it returns a string. Basically you will call it like: Microsoft.VisualBasic.Interaction.InputBox("Give me a value.");. The only thing you have to do before you do this, is add Microsoft.VisualBasic.dll as a reference. This will make getting input with separate windows a lot easier. I know it's not very relevant with the thread but it will shorten your code a fair amount.
Was This Post Helpful? 0
  • +
  • -

#15 John316  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 03-May 11

Re: Displaying Contents of List in TextBox - Windows Form Application

Posted 22 May 2011 - 06:32 AM

Hello all,

Still having trouble getting this application to work!
The problem is getting the list items (customers) to display in the listbox on form1.
From form1 the user selects the add new customer button which takes the user to a new form to enter the customers name,address,telephone and email into text boxes. When the details have been entered the user hits the add customer button which should send the entered customer details into a list(Customers). The user then returns to the main menu(Main Menu button).
From mainmenu(form1) the user then hits show customer button to display the list items in a listbox contained in form1.

The error i am getting after hitting show customers is:NullReferenceException was Unhandled (Object reference not set to an instance of an object) on these line of the code:

  foreach (var customer in customerStore.Customers)
            {
                customerListBox.Items.Add(customer);
            }



Any help with this would be much appreciated. I have included the full code below to give the bigger picture.
 public class Customer
    {
        public Customer(string fullname, string address, string telephoneNumber, string emailAddress)
        {
            FullName = fullname;
            Address = address;
            TelephoneNumber = telephoneNumber;
            EmailAddress = emailAddress;
        }

        // Properties     
        public override string ToString()
        {
            return string.Format("{0} : {1} : {2} : {3}", FullName, Address, TelephoneNumber, EmailAddress);
        }

        public string FullName
        {
            get; private set;         
        }

        public string Address
        {
            get; private set;

        }

        public string TelephoneNumber
        {
            get; private set;

        }

        public string EmailAddress
        {
            get; private set;
        }
    }



 class CustomerStore
    {          
        public CustomerStore()
        { 
            Customers = new List<Customer>();
        }

        public void AddCustomer(Customer customer)
        {
            Customers.Add(customer);                // Enables customers to be added to list
        }

        public List<Customer> Customers
        {
            get;
            private set;
        }
    }


 public partial class AddCustomer : Form
    {
        public AddCustomer()
        {
            InitializeComponent();           
        }

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

           

        public Customer NewCustomer
        {
            get;
            private set;
        }


        private void okButton_Click_1(object sender, EventArgs e)
        { 
         NewCustomer = new Customer(fullNameTextBox.Text, addressTextBox.Text, telephoneNumberTextBox.Text, emailTextBox.Text);
        }
    }


 public partial class Form1 : Form
    {
        public Form1()
        {            
            InitializeComponent();
           
        }

       private void Main_Load(object sender, EventArgs e)
        {

        }
 
        private void addNewCustomerButton_Click(object sender, EventArgs e)
        {
            AddCustomer addCustomerForm = new AddCustomer();
            if (DialogResult.OK == addCustomerForm.ShowDialog())
            {
                customerStore.AddCustomer(addCustomerForm.NewCustomer);
            }
        }

        private CustomerStore customerStore;
        
        private void Form1_Load(object sender, EventArgs e)
        {
            customerStore = new CustomerStore();
        }
        
        private void displayCustomersButton_Click(object sender, EventArgs e)
        {
            customerListBox.Items.Clear();

            foreach (var customer in customerStore.Customers)
            {
                customerListBox.Items.Add(customer);
            }

        }
        

        private void customerListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }
    }


Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3