Title: Determine whether a year is a leap year in C#
Detecting leap years is practically trivial because the DateTime data type provides an IsLeapYear method to do just this. The example uses the following code to display the leap years between the two entered dates.
// List leap years between the two entered years.
private void btnList_Click(object sender, EventArgs e)
{
lstYears.Items.Clear();
int from_year = int.Parse(txtFromYear.Text);
int to_year = int.Parse(txtToYear.Text);
for (int year = from_year; year <= to_year; year++)
{
if (DateTime.IsLeapYear(year)) lstYears.Items.Add(year);
}
}
The code uses int.Parse to convert the entered year numbers from strings into integers. It then loops over the years within the indicated range and adds a year to the ListBox if DateTime.IsLeapYear returns true.
Download the example to experiment with it and to see additional details.
|