gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:05:58 24 4
gpt4 key购买 nike

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com