我有一个列表框,当前正在从我的数据库中读取字段。我希望能够将我正在阅读的每个单独的值存储为字符串和整数。将有四种字段类型,分别是Surname,Forename,EmployeeID,PaymentDate。如何将选定的组合字段项拆分并存储为单独的变量。
foreach (DataRow dr in dsEmployeePayment.Tables["EmployeePayment"].Rows)
{
lstPaymentID_Edit.Items.Add(
dr["Surname"].ToString() + ", "
+ dr["Forename"] + ", "
+ dr["EmployeeID"].ToString() + ", "
+ dr["PaymentDate"].ToString());
}
答案 0 :(得分:1)
考虑为要添加到ListBox
的项目创建一个对象。
public class Employee
{
public string Surname { get; set; }
public string Forename { get; set; }
public int EmployeeID { get; set; }
public DateTime PaymentDate { get; set; }
public override string ToString()
{
return string.Join(", ", Surname, Forename, EmployeeID, PaymentDate);
}
}
您的课程将包含正确类型的所有字段。 ListBox
会在您的商品上调用ToString
,并以与您现在相同的方式显示。
DataRow
处理将如下所示:
foreach (DataRow dr in dsEmployeePayment.Tables["EmployeePayment"].Rows)
{
lstPaymentID_Edit.Items.Add(
new Employee {
Surname = (string)dr["Surname"],
Forename = (string)dr["Forename"],
EmployeeID = (int)dr["EmployeeID"],
PaymentDate = (DateTime)dr["PaymentDate"]
}
);
}
当您对所选项目执行某些操作时,会发生真正的魔法:
Employee selectedEmployee = lstPaymentID_Edit.SelectedItem as Employee;
DateTime paymentDate = selectedEmployee.PaymentDate;