繁体   English   中英

从另一个类C#添加列表框项目

[英]add listbox items from another class C#

大家好,我正在尝试将另一个类的值添加到MainForm上的ListBox中,但是我收到未处理的错误NullReferenceException。 这是我的代码:

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**

      }

    }
}

有什么建议么

您尚未创建MainForm类并且拼写了customerName:

私人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**

  }

您的实例变量表示:

 private string customerName = "Me ";

但是您的代码引用了这一点:

costumerName

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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