显示列表C#中的日期

时间:2015-12-05 18:55:38

标签: c# winforms

我正在尝试在list内显示ListBox的日期。为此,我尝试将list绑定到listbox

以下是我的驱动程序类的代码。

public class Driver
{
    private string name;
    private string occupation;
    private DateTime dateOfBirth;
    private List<DateTime> dateOfClaim;

    public Driver(string name, string occupation, DateTime dateOfBirth, List<DateTime> dateOfClaim)
    {
        this.name = name;
        this.occupation = occupation;
        this.dateOfBirth = dateOfBirth;
        this.dateOfClaim = dateOfClaim;
    }

    public string DriverName
    {
        get{ return name; }
        set{ name = value; }
    }

    public string DriverOccupation
    {
        get { return occupation; }
        set { occupation = value; }
    }

    public DateTime DriverDateOfBirth
    {
        get { return dateOfBirth; }
        set { dateOfBirth = value; }
    }

    public List<DateTime> DriverDateOfClaim
    {
        get { return dateOfClaim; }
        set { dateOfClaim = value; }
    }
}

我有一个button,可让您为驱动程序添加date索赔,最多可提出5个索赔。我有一个“临时”list,在dateOfClaim list中分配给Driver list之前保留这些日期,因为尚未创建新的驱动程序对象。

以下是声明和填充arraylist的表单中的部分代码。

private List<Driver> drivers = new List<Driver>();
private List<DateTime> claimDates = new List<DateTime>();

if (noOfClaims <= 4)
{
    claimDates.Add(dtpAddClaim.Value.Date);
    noOfClaims++;
}

if (noOfDrivers <= 4)
{
    drivers.Add(new Driver(txtName.Text, txtOccupation.Text, dtpDOB.Value.Date, claimDates));
    noOfDrivers++;
}

要将dateOfClaim list绑定到listbox,我尝试使用以下代码,但列表框中没有显示任何内容。

lstClaimDates.DataSource = drivers;
lstClaimDates.DisplayMember = "DriverDateOfClaim";

我已尝试使用以下代码在标签中显示日期,但同样没有任何显示让我相信我没有正确添加dateOfClaim list

foreach (DateTime d in drivers[0].driverDateOfClaim)
    label1.Text += d.ToString() + " ";

任何帮助解决这个问题都将非常感激。

2 个答案:

答案 0 :(得分:1)

你可以将它们绑定为字符串,例如使用Linq

lstClaimDates.DataSource = drivers[i].driverDateOfClaim.Select(d => d.ToString()).ToList();

应该完成这项工作(您可以在ToString调用中指定日期格式)

答案 1 :(得分:1)

<强>的WinForms:

您需要定义要在listBox中显示的值/字段/属性:

List<Driver> drivers = new List<Driver>();   
drivers.Add(new Driver("name", "The Earth", DateTime.Now, null));
listBox1.DataSource = drivers;
listBox1.DisplayMember = "drivername";

更新0:

如果它不适合您,请告诉我:

foreach (var c in drivers[0].driverDateOfClaim)
{
   listBox1.Items.Add(c);
}

Magnus Montin是超级程序员,他是shows another solution

List<Driver> drivers = new List<Driver>();            
drivers.Add(new Driver("name", "The Earth", DateTime.Now, new List<DateTime>() { 
            DateTime.Now, 
            DateTime.Now, 
        } ));
listBox1.DataSource = drivers[0].driverDateOfClaim;

更新1:

 List<Driver> drivers = new List<Driver>();            
 drivers.Add(new Driver("name", "The Earth", DateTime.Now, new List<DateTime>() 
     { 
        DateTime.Now, 
        DateTime.Now, 
        } ));
 foreach (var c in drivers[0].driverDateOfClaim)
 {
   textBox1.Text += " | " + c;
 }