加载事件似乎没有被调用

时间:2014-03-30 12:45:51

标签: c# events

我正在尝试在load事件中初始化我的数组的元素(这是类的数组),但它没有被调用,也无法看到我做错了什么。

这是我的代码:

namespace Coffee_Shop_Login
{
    public partial class frmLogin : Form
    {
        public frmLogin()
        {
            InitializeComponent();
        }

        //Global Variables
        static int Maximum_Number_Of_Logins = 1;
        LoginDetails[] Employees = new LoginDetails[Maximum_Number_Of_Logins];//creating array of objects of type LoginDetails


        //method initialises the array objects when form loads
        private void frmLogin_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < Employees.Length; i++)
            {
                Employees[i] = new LoginDetails(); // set up single element to a new instance of the object
            }
        }//end of frmLogin_Load() 

        private void btnLogin_Click(object sender, EventArgs e)
        {
            string username = "Johnny";
            Employees[0].Set_Employee_Username(username);
            MessageBox.Show("Username is: " + Employees[0].Get_Employee_Username());
        }
    }
}

namespace Coffee_Shop_Login
{
    class LoginDetails
    {
        //Public Mutator Functions
        //========================

        public void Set_Employee_Username(string username)
        {
            Employee_Username = username;//sets Employee_Username with value passed in
        }//end of Set_Employee_Username()


        public void Set_Employee_Password(string password)
        {
            Employee_Password = password;//sets Employee_Password with value passed in
        }//end of Set_Employee_Password()        


        //Public Accessor Functions
        //=========================

        public string Get_Employee_Username()
        {
            return Employee_Username;//returns the value of Employee_Username
        }//end of Get_Employee_Username()


        public string Get_Employee_Password()
        {
            return Employee_Password;//returns the value of Employee_Password
        }//end of Get_Employee_Password()


        //Private Member Variables
        private string Employee_Username;
        private string Employee_Password;

    }
}

当我运行应用程序时,由于未调用load事件,我收到此错误消息:

  

未处理的类型&#39; System.NullReferenceException&#39;发生在Coffee Shop Login.exe

     

附加信息:未将对象引用设置为对象的实例。

我需要添加什么才能使Load事件调用我的方法?

1 个答案:

答案 0 :(得分:0)

尝试在表单构造函数中实例化数组,而不是在类中实例化,如下所示:

public frmLogin()
    {
        InitializeComponent();
        Employees = new LoginDetails[Maximum_Number_Of_Logins];
    }