Populate combo box for month and year in c#

Hi to all.

In this post we populate combo box for month and year.

First take two combo box one for month and second for year.Name them CmbMonth and CmbYear.

we create function for fill data in combo box.

year

For month combo box

        private void Fill_CmbMonth()
        {
            try
            {
             
               //clear all data from combobox
                CmbMonth.Items.Clear();
                //add default item
                CmbMonth.Items.Add("Select");
                //fill array from System.Globalization.DateTimeFormatInfo.InvariantInfo
                var Months = System.Globalization.DateTimeFormatInfo.InvariantInfo.MonthNames;
                //loop array for add items
                foreach (string sm in Months)
                {
                    if(sm!="")
                        CmbMonth.Items.Add(sm);
                }
                //set selected item for display on startup
                CmbMonth.Text = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Month);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

 For year combo box

        private void Fill_CmbYear()
        {
            try
            {
               //clear all data from combobox
                CmbYear.Items.Clear();
                //add default item
                CmbYear.Items.Add("Select");
               //loop array for add items
                for (int i = DateTime.Now.Year; i < DateTime.Now.Year + 15; i++)
                {
                    CmbYear.Items.Add(i);
                }
                //set selected item for display on startup
                CmbYear.Text = DateTime.Now.Year.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

Now on load time just call this functions to populate combo box.

In first function we use System.Globalization.DateTimeFormatInfo.InvariantInfo for get array of month list. And in second function we set current year as start index and loop for 15 years.

For manually add item in combo box we use :  ComboBox.Items.Add("item");

Thanks for read.

Comments

Popular posts from this blog

How to get month days count from date or month and year

CRUD Operations in win form application with access database