我有一个列表框,当前正在从数据库中读取字段。我希望能够将要读取的每个单独的值存储为字符串和整数。将有四个字段类型,分别是姓,名,雇员ID,付款日期。如何将合并的字段的选定项目拆分和存储为单独的变量。
foreach (DataRow dr in dsEmployeePayment.Tables["EmployeePayment"].Rows)
{
lstPaymentID_Edit.Items.Add(
dr["Surname"].ToString() + ", "
+ dr["Forename"] + ", "
+ dr["EmployeeID"].ToString() + ", "
+ dr["PaymentDate"].ToString());
}
最佳答案
考虑为要添加到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;
关于c# - 将列表框中的各个值存储为变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30792587/