Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

C# Windows forms combobox leap year

c# winforms

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1 toragoroshi


    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 06 February 2015 - 08:30 PM

I'm trying to write a program that contains 3 comboboxes (1 for year, 1 for month, 1 for day). I managed to dig enough to find the proper codes to display the years, months, and the number of days according to the selected month (...31 for January, 30 for April...). Now I have to have a process that checks if the selected year in my years combobox is a leap year, just to February would have 29 days if the year is indeed a leap year.


Here's the code I used:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Globalization;

namespace WindowsFormsApplication1
    public partial class Form1 : Form
        public Form1()

            DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(null);

            for (int year = 1950; year <= DateTime.Today.Year; year++)

            //var months = DateTimeFormatInfo.InvariantInfo.MonthNames;
           // monthBox.DataSource = months;

            for (int i = 1; i < 13; i++)


        private void Form1_Load(object sender, EventArgs e)

        private void yearBox_SelectedIndexChanged(object sender, EventArgs e)

        private void monthBox_SelectedIndexChanged(object sender, EventArgs e)
            ComboBox c = sender as ComboBox;
            int index = c.SelectedIndex;
            if(index >= 0)
                index++;  // Index start at zero, months start at 1
                int days = DateTime.DaysInMonth(DateTime.Today.Date.Year, index);
                var range = Enumerable.Range(1, days);
                dayBox.DataSource = range.ToList();

        private void dayBox_SelectedIndexChanged(object sender, EventArgs e)

the yearBox is for the year combo, the monthBox for the month combo, and dayBox for the days combo.


Should I use the DateTime.IsLeapYear method or is there an easier way to do it?


Thanks guys and stay awesome!

Edited by toragoroshi, 06 February 2015 - 08:37 PM.

#2 BlackRabbit


    CodeCall Legend

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3871 posts

Posted 07 February 2015 - 07:57 AM

You should definitely use the calendar control instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download