将列表框中的单个值存储为变量

Storing Individual Values From List Box As Variables

我有一个列表框,它当前正在从我的数据库中读取字段。我希望能够将我正在读取的每个单独的值存储为字符串和整数。将有四种字段类型,分别是 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());
}

考虑为要添加到 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);
    }
 }

您的 class 将包含正确类型的所有字段。 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;