-1

到目前为止,我做到了,但它不起作用,而不是让我知道它删除所有列表项的具体日期,请帮忙

private void button1_Click_1(object sender, EventArgs e)
{
    List<RentalCar> listBox1snew = new List<RentalCar>();
    for (int i = 0; i < listBox1s.Count; i++)
    {
        if ((DateTime.Now.Day - listBox1s[i].WOF.Day) <= 7)
        {
            listBox1.Items.Insert(0, listBox1snew[i]);

        }
    }
    listBox1.DataSource = listBox1snew;//add car to listbox
}
4

4 回答 4

1
listBox1.Items.Insert(0, listBox1snew[i]);

这是没有意义的。listBox1snew的。我相信你的意思listBox1s[i]

listBox1.DataSource = listBox1snew;

这更没有意义。首先,您在其中插入项目,listBox1.Items然后覆盖DataSource,实际上忽略了Items. 另外,您没有listBox1snew以任何方式修改,所以它仍然是空的!

认为你追求的是:

  • 将元素从 复制listBox1slistBox1snew
  • 设置DataSourcelistBox1snew

那看起来像:

private void button1_Click_1(object sender, EventArgs e)
{
    List<RentalCar> listBox1snew = new List<RentalCar>();
    for (int i = 0; i < listBox1s.Count; i++)
    {
        if (DateTime.Now.Subtract(listBox1s[i].WOF).Days <= 7)
        {
            // Copy from listBox1s to listBox1snew
            listBox1new.Add(listBox1s[i]);
        }
    }
    // Use listBox1new as new data source
    listBox1.DataSource = listBox1new;
}

此外,您可以使用 LINQ 轻松表达此过滤器:

private void button1_Click_1(object sender, EventArgs e)
{
    listBox1.DataSource = listBox1s.Where(x => DateTime.Now.Subtract(x.WOF).Days <= 7).ToList();
}
于 2013-01-20T10:05:46.843 回答
1

首先,您检查日期的逻辑应该是:

DateTime.Now.Subtract(listBox1s[i].WOF).Days <= 7

您将 ListBox 数据源设置为 listBox1snew,但您从未向 listBox1snew添加任何内容!

于 2013-01-20T10:02:49.880 回答
0

您应该先减去两天,然后找到天差。

private void button1_Click_1(object sender, EventArgs e)
    {
        List<RentalCar> listBox1snew = new List<RentalCar>();
        for (int i = 0; i < listBox1s.Count; i++)
        {
            if ((DateTime.Now - listBox1s[i].WOF).Days <= 7)
            {
                listBox1snew .Items.Insert(0, listBox1s[i]);

            }
        }
        listBox1.DataSource = listBox1snew;//add car to listbox
    }
于 2013-01-20T10:04:50.707 回答
0
DateTime.Now.AddDays(-7) <= listBox1s[i].WOF
于 2013-01-20T10:04:13.183 回答