2016-12-06 58 views
0

我想要做的是保存列表框的所有填充参考键列表。将有未知数量的线路(用户/“患者”)。保存列表后,我希望能够使用列表框索引来查找相应的键,并使用它来转到下一部分。正在初始化数据引用的字符串数组

public partial class PatientList : Window 
{ 
    HumanResources ListAllPatients; 
    List<PatientInformation> AllPatients; 
    string[] Usernames; 

    public PatientList() 
    { 
     InitializeComponent(); 
     int i = 0; 
     string[] Usernames = new string[i]; 
     ListAllPatients = new HumanResources(); 
     AllPatients = ListAllPatients.PopPatientList(); 

     foreach (PatientInformation PatientChoice in AllPatients) 
     { 
      Usernames[i] = PatientChoice.Username; 
      lboxPatients.Items.Add(string.Format("{0} {1}; {2}", PatientChoice.FirstName, PatientChoice.LastName, PatientChoice.Gender)); 
      i += 1; 
     } 
    } 

这里是你移动到下一个部分的按钮的代码

public void btnSelectPatient_Click(object sender, RoutedEventArgs e) 
    { 
     PatientInfo PatientInfoWindow = new PatientInfo(); 
     PatientInfoWindow.Show(); 
     //i = lboxPatients.SelectedIndex; 
     //UserFactory.CurrentUser = Usernames2[i]; 
     this.Close(); 
    } 

我的问题是这样的:我相信我已经初始化字符串数组来做到这一点,但保持VS告诉我它没有被分配到,并且一直保持为空。

我的问题:为了完成从P​​atientList()向btnSelectPatient发送密钥,我如何以及在哪里正确初始化字符串数组(或更好的方法)?

+0

你在哪里初始化它? –

+0

我相信我已经初始化它在最上面,在List AllPatients – Erick

回答

0

初始化string[]领域,但在构造这里的局部变量:

string[] Usernames; 

public PatientList() 
{ 
    InitializeComponent(); 
    int i = 0; 
    string[] Usernames = new string[i]; 

你必须指定这个数组领域:

public PatientList() 
{ 
    InitializeComponent(); 
    int i = 0; 
    this.Usernames = new string[i]; 

但是,没有按”因为它的长度总是0.

也许你想要这个:

public PatientList() 
{ 
    InitializeComponent(); 
    ListAllPatients = new HumanResources(); 
    AllPatients = ListAllPatients.PopPatientList(); 
    this.Usernames = new string[AllPatients.Count]; 

    int i = 0; 
    foreach (PatientInformation PatientChoice in AllPatients) 
    { 
     Usernames[i] = PatientChoice.Username; 
     lboxPatients.Items.Add(string.Format("{0} {1}; {2}", PatientChoice.FirstName, PatientChoice.LastName, PatientChoice.Gender)); 
     i += 1; 
    } 
} 
+0

之后,感谢Tim,最后一点点是我需要的。 – Erick

0

你有几个错误:

  • 你初始化一个新的局部变量,而不是类级别的变量,因为你再次声明(string[] userNames = ...
  • 你的初始化长度为0的数组。当您尝试将项目添加到位置1和以上时,这会失败。

我的建议是使用一个列表,因为它更适合于动态长度列表,您不需要保证指数的跟踪自己,它会自动将正确的索引处添加:

HumanResources ListAllPatients; 
List<PatientInformation> AllPatients; 
List<string> Usernames = new List<string>(); 

public PatientList() 
{ 
    InitializeComponent(); 
    ListAllPatients = new HumanResources(); 
    AllPatients = ListAllPatients.PopPatientList(); 

    foreach (PatientInformation PatientChoice in AllPatients) 
    { 
     Usernames.Add(PatientChoice.Username); 
     lboxPatients.Items.Add(string.Format("{0} {1}; {2}", PatientChoice.FirstName, PatientChoice.LastName, PatientChoice.Gender)); 
    } 
}