简体   繁体   中英

add listbox items from another class C#

Hi everyone I am trying to add values from another class to a ListBox on the MainForm however I am receiving the error NullReferenceException was unhandled. Here is my code:

public partial class MainForm : Form
{      
    Seats currentSeat = new Seats();

    public MainForm()
    {
        InitializeComponent(); // VS' s code

        //1. Prepare the form before it is shown to the user.
        InitializeGUI();
    }

    private void InitializeGUI()
    {           
        currentSeat.Seat();
    }

**class Seats**
{

    private string customerName = "Me ";

    MainForm mainForm;

    public void Seat()
    {
      SetDefaultValues();
    }

  private void  SetDefaultValues(){

      for (int seat = 1; seat <= 60; seat++)
      {            
          mainForm.listBoxReservations.Items.Add(string.Format("{0} {1} ", seat,costumerName)); // **HERE IS THE ERROR NullReferenceException was unhandled**

      }

    }
}

Any suggestions

You have not created the MainForm class AND have misspelled customerName:

private void SetDefaultValues(){

  for (int seat = 1; seat <= 60; seat++)
  {            
      mainForm.listBoxReservations.Items.Add(string.Format("{0} {1} ",    seat,costumerName)); // **HERE IS THE ERROR NullReferenceException was unhandled**

  }

Your instance variable says this:

 private string customerName = "Me ";

But your code refers to this:

costumerName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM