简体   繁体   中英

how to get the next coming seven days in my listbox and remove the others?

so far i did that but it doesnt work instead of getting me the specific date it erase all the list items please help

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
}

First of all your logic to check for the date should be:

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

You're setting the ListBox datasource to listBox1snew but you're never Adding anything to listBox1snew!

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

This makes no sense. listBox1snew is empty . I believe you meant listBox1s[i] .

listBox1.DataSource = listBox1snew;

This makes even less sense. First, you're inserting items in listBox1.Items and then you override the DataSource , effectively ignoring the Items . Also, you didn't modify listBox1snew in any way, so it will still be empty !

What I think you're after:

  • Copy elements from listBox1s to listBox1snew .
  • Set the DataSource to listBox1snew .

That would look like:

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;
}

Also, you could easily express this filter with LINQ:

private void button1_Click_1(object sender, EventArgs e)
{
    listBox1.DataSource = listBox1s.Where(x => DateTime.Now.Subtract(x.WOF).Days <= 7).ToList();
}
DateTime.Now.AddDays(-7) <= listBox1s[i].WOF

You should subtract the two days first then find days difference.

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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM