Reputation: 5539
I have this code on selected index changed of a dropdownlist which represents months.
DateTime firstDate, lastDate;
int mon = DropDownList1.SelectedIndex +1;
int year = 2013;
GetDates(mon, year,out firstDate , out lastDate);
DateTime f = firstDate;
DateTime d2 = firstDate.AddDays(7);
for (;d2.Month == mon; )
{
d2.AddDays(7); // value after first iteration is "08-Apr-13 12:00:00 AM"
// but beyond first iteration the value remains the same.
}
private void GetDates(int mon, int year, out DateTime firstDate, out DateTime lastDate)
{
int noOfdays = DateTime.DaysInMonth(year, mon);
firstDate = new DateTime(year, mon, 1);
lastDate = new DateTime(year, mon, noOfdays);
}
I was hoping that d2 will keep getting incremented by 7 days in each iteration as long as resulting value is in the same month. But it seems that the value increments just once. i.e from 01-Apr-13 12:00:00 AM to 08-Apr-13 12:00:00 AM
Upvotes: 3
Views: 1336
Reputation: 148120
You have to assign changed date object back to date object d2
because DateTime object is immutable. AddDays
method returns new object instead of changing the object on which it is called so you have to assign it back to calling object.
d2 = d2.AddDays(7);
Edit Why it works for first iteration ?
Because you are intializing the date object by add 7 days before loop.
DateTime d2 = firstDate.AddDays(7);
Upvotes: 13