2014-03-30 59 views
1

我想在加载事件中初始化我的数组(这是一个类的数组)的元素,但它没有被调用,看不到我是什么做错了。加载事件似乎并没有被调用

这是我的代码:

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; 

    } 
} 

当我运行应用程序,我收到此错误信息,由于没有被调用加载事件:

类型的未处理的异常“System.NullReferenceException '发生在咖啡店Login.exe

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

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

+0

你能告诉我哪行,你所得到的错误?除了使用C#编写类似Java代码的糟糕风格之外,我没有找到任何理由说明为什么您的代码无法正常工作,因为它对我来说运行良好。错误可能在其他地方。有了这个说法,认真考虑首先学习C#及其基础知识,像属性和相关约定。 –

+0

我只能看到的是'frmLogin_Load'方法没有在事件中注册,它在点击按钮 –

+0

Alexandre时创建了一个NRE,我同意问题出在我的加载事件上,但我相信我遵循了正确的格式和正确的名称,所以不明白为什么它不会运行。 – user3478049

回答

0

尝试实例的形式构造阵列,而不是无处类,像这样:

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

感谢卡里姆,它现在正在工作。但是,我不明白为什么我的加载事件不会执行。 – user3478049

+0

语言规范禁止在类级别执行任意语句..参考此[**答案**](http://stackoverflow.com/questions/13198167/why-cant-i-set-the-property类对象 - 无法在一个方法中)以获取更多信息 –

相关问题