2016-12-06 70 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)); 
    } 
}