For loop Step???

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am building a dropdown select box for year and want to render the dropdown
in reverse order. Using VB I could use step, but I am unsure how to do this
in C#

Any help would be great.

if (!this.IsPostBack)
{
for (int i = 2000; i <= DateTime.Now.Year; i++)
{
int intSubtractTerm = 0;
ListItem newListItem = new ListItem();
intYear = DateTime.Now.Year;
intSubtractTerm = intYear - i;
intYear = intYear - intSubtractTerm;
newListItem.Value = intYear.ToString();
newListItem.Text = intYear.ToString();
DropDownListYear.Items.Add(newListItem);
}
}
 
for (int i = 2000; i <= DateTime.Now.Year; i++)

To reverse the loop from 2000 to DateTime.Now.Year:

for (int i = DateTime.Now.Year; i >= 2000; i--)
{
[...]
}

int i = DateTime.Now.Year -- creates 'i', and sets it to the current Year
i >= 2000 -- continues looping as long as 'i' is greater than or equal to 2000
i-- -- decrements 'i' by one before checking (i >= 2000) -- this only happens after the
first loop
 
Moojjoo said:
I am building a dropdown select box for year and want to render the dropdown
in reverse order. Using VB I could use step, but I am unsure how to do this
in C#

You need to understand the three parts of the for loop:

1) The initialisation step (int i=2000)
2) The condition to be verified on each iteration
(i <= DateTime.Now)
3) The code to be executed on iteration to "move" the loop on
(i++)

Given those parts, the equivalent of "step" is the third part - so you
need to change the initialisation to go from the end, change the
condition to check whether you've hit the lowest date or not, and
change the third part to decrement i instead of incrementing it.
 
Back
Top