user3345212
user3345212

Reputation: 131

DropDownList Dynamic Data - ASP.Net

I am adding to my dropdownlist the first day of the this month and the next two months, The problem is, when I tested this for November, it is going like that:

11/01/2014 12/01/2014 01/01/2014

AS you see, the 01/01/2014 is wrong, it needs to be 01/01/2015, I am not sure how to start this, any suggestions are appreciated. Thank you.

This is my code:

for (int i = 0; i < 3; i++)
{
    DateTime dt = DateTime.Now;
    DateTime dayone = new DateTime(dt.AddMonths(1).Year, dt.AddMonths(+i).Month, 1);
    DropDownList3.Items.Add(dayone.ToString("MM/dd/yyyy"));
}

Upvotes: 0

Views: 63

Answers (1)

LUKE
LUKE

Reputation: 1375

Short answer is dt.AddMonths(1).Year will always be next month's year. So, next month is November which is still 2014 and you'll have that in every loop.

This is probably better refactored as:

DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
for (int i = 0; i < 3; i++)
{
    DropDownList3.Items.Add(dt.AddMonths(i).ToString("MM/dd/yyyy"));
}

Upvotes: 2

Related Questions