就像標題所暗示的,我試圖用csv中的信息填充WPF應用程序中的列表框。理想情況下,我想顯示csv中的每一行,但只顯示某些列,例如健身數據,我會顯示名字,姓氏,出生日期,性別等信息,但我只會顯示姓氏和名字。我的代碼如下:從csv通過列表填充列表框<>
public partial class PatientList : Window
{
int x = 0;
public PatientList()
{
InitializeComponent();
HumanResources ListAllPatients = new HumanResources();
List<PatientInformation> AllPatients = ListAllPatients.PopPatientList();
foreach (PatientInformation PatientChoice in AllPatients)
{
lboxPatients.Items.Add(AllPatients[x]);
x += 1;
}
}
人力資源類
public List<PatientInformation> PopPatientList()
{
DataAccess PatientList4Doc = new DataAccess();
List<PatientInformation> DocsPatients = PatientList4Doc.ListofPatients();
return DocsPatients;
}
數據訪問類
class DataAccess
{
public List<PatientInformation> ListofPatients()
{
List<PatientInformation> ListofPatients = new List<PatientInformation>();
string[] UserData = File.ReadAllLines("UserList.csv");
foreach (string Person in UserData)
{
string[] PersonInfo = Person.Split(',');
PatientInformation Patient = new PatientInformation()
{
Username = PersonInfo[0].ToUpper(),
LastName = PersonInfo[1],
FirstName = PersonInfo[2],
DOB = Convert.ToDateTime(PersonInfo[3]),
Gender = Convert.ToChar(PersonInfo[4]),
Height = Convert.ToInt16(PersonInfo[5]),
Weight = Convert.ToInt16(PersonInfo[6]),
CaloricIntake = PersonInfo[7],
WaterDrank = PersonInfo[8],
CaloriesBurned = PersonInfo[9],
TimeSlept = PersonInfo[10],
ContextMessage = PersonInfo[11],
Replymessage = PersonInfo[12]
};
ListofPatients.Add(Patient);
}
return ListofPatients;
}
病人信息類
public class PatientInformation
{
public string Username { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public DateTime DOB { get; set; }
public char Gender { get; set; }
public int Height { get; set; }
public int Weight { get; set; }
public string CaloricIntake { get; set; }
public string WaterDrank { get; set; }
public string CaloriesBurned { get; set; }
public string TimeSlept { get; set; }
public string ContextMessage { get; set; }
public string Replymessage { get; set; }
}
一切工作正常,直到我嘗試填充l istbox。當我嘗試讀取信息時,我所得到的只是代碼路徑而不是所需的信息。我的問題是:一旦將所有信息從CSV中提取出來,我怎樣才能將它打印到列表框中並讓它顯示來自PatientInformation的內容?在此先感謝您的幫助
編輯
@Hypnos:我實現了你的建議,像這樣:
I tried implementing your example like so: HumanResources ListAllPatients = new HumanResources();
List<PatientInformation> AllPatients = ListAllPatients.PopPatientList();
List<PatientInformation> p = new List<PatientInformation>();
p.Add(new PatientInformation() { Username = Convert.ToString(AllPatients[0]), FirstName = Convert.ToString(AllPatients[2]), LastName = Convert.ToString(AllPatients[1]) });
lboxPatients.ItemsSource = p;
然而,這會返回一個異常「索引超出範圍必須爲非負值且小於集合的大小「