JavaScript Error

You currently have JavaScript disabled on your web browser.

This website uses JavaScript, and This web page needs JavaScript activated to work correctly.

Please active JavaScript on your web browser and then refresh this web page.



MonthCalendar



example1

The MonthCalendar control is found in the System.Windows.Forms namespace within the System.Windows.Forms.dll. In this blog post I am referring to the MonthCalendar control that is available in C# .NET-Core (.NET 6.0) with Visual Studio 2022 (although this code example might still work OK with older .NET versions).

The purpose and function of the MonthCalendar control is to represent a visual monthly calendar display which the user can view and select dates from, in a standard Gregorian style calendar.

The visual appearance of the MonthCalendar control object can be modified to some extent by adjusting the ForeColor, Font, TitleBackColor, TitleForeColor, TrailingForeColor, and BackColor properties. Since the Paint event is never raised for this control, if you need to provide a more customized look then you should override the OnPrint method and perform custom painting.


Example Source Code

This example uses a MonthCalendar control, along with a GroupBox control, two Label controls, two TextBox controls, two RadioButton controls, one Button control, and a MessageBox object.

To add the MonthCalendar control to your form, you can double click on its name (i.e. MonthCalendar) as listed in the Toolbox window panel within the Form editor window. Alternatively, you can single click on it and then drag and drop it onto your form, to position it more closer to where you want it to be positioned at. Once it is added to the form then it will appear on the forms surface area having default control values.

After you have added the MonthCalendar control to your form, then once you select it then you can view and edit that objects property values in the Properties window within the Forms editor window, where you can then change the controls Name, Text, and other properties as you desire.

The following example shows how a MonthCalendar control can be added to a Form and allow a user to view and add both recurring Birthday and fixed Appointment date's to the calendar, which will display on the calendar as Bold date values.

In the following example, I added a MonthCalendar control to my Form, positioning it so that it is centered horizontally and near the top of the form, as shown below. After selecting it I altered its Anchor property to only be anchored at the Top, so that the object will auto-center itself horizontally on the form whenever the form is resized by the user. I then double clicked onto the MonthCalendar control object so that Visual Studio will automatically create and link a callback method to the controls DateChanged event into the Forms source code.

I then added a Label control, and changed its Text property to "Personal Calendar" and altered its Font and ForeColor property values, to increase its size and make it look pleasing. I positioned it to be at the very top of the form and centered above the MonthCalendar control object, and then set its Anchor property to only be anchored at the Top also, so that it too will auto-center itself horizontally on the form whenever the form is resized by the user.

Then I added a GroupBox control, and added a TextBox, two Radio buttons, and one Button control into it, along with some Label controls to help visually identify them to the user. I then altered their Text properties to display the string values as is shown on the Form below. I set the GroupBox and TextBox controls Anchor property to Left, Right, and Top, so that they will stretch with the Form if the user resizes the Form, and then I set the Button controls Anchor property to Right and Top so that its position floats at a fixed distance from the Top and Right edges of the Form if the user resizes the Form.

I then double clicked on the Button control object so that Visual Studio will automatically create and link a callback method to that button's Click event into the Forms source code.

I then added a TextBox control to the bottom of the Form, and set its MultiLine property to True. I then resized it to be the width of the Form, and anchored it Left, Right and Bottom so that it too will stretch with the Form if the user ever resizes the Form. I set the TextBox's ScrollBar property value to Both, and ReadOnly property value to True.

example2

I then altered and expanded upon the Forms source code as shown below:

 
// Copyright 2024 T&J Divisions, LLC	
// Designed and developed by Tim Tolbert
// All Rights Reserved
namespace TestProgram
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // initialize MonthCalendar control
            monthCalendar1.TodayDate = DateTime.Today;

            // load birthdates
            loadBirthDates();

            // load appointments
            loadAppointments();

            // populate calendar with known birthdates
            reloadCalendar();

            // display the records for this date, if any
            displaySelectedDatesRecords();
        }

        private void displaySelectedDatesRecords()
        {
            // get the selected date value
            DateTime thisDate = monthCalendar1.SelectionStart;
            string thisDateText = thisDate.ToString("MM/dd/yyyy");
            string shortDate = thisDate.ToString("MM/dd/");

            // see if this is a birth date
            string thisValue = "-------------------" + Environment.NewLine;
            foreach (KeyValuePair<string, string> thisBirthDay in birthDates)
            {
                if (thisBirthDay.Key.StartsWith(shortDate) == true)
                {
                    thisValue += "Birthday: " + thisBirthDay.Key + "  " + thisBirthDay.Value + Environment.NewLine;
                }
            }

            // see if this is an appointment
            foreach (KeyValuePair<string, string> thisAppointmentDay in appointmentDates)
            {
                if (thisAppointmentDay.Key.StartsWith(shortDate) == true)
                {
                    thisValue += "Appointment: " + thisAppointmentDay.Key + "  " + thisAppointmentDay.Value + Environment.NewLine;
                }
            }

            // give feedback
            textBox2.Text = thisDateText + Environment.NewLine + thisValue;

            // update the new date records group box text
            groupBox1.Text = "New Date Record for " + thisDateText;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // precheck
            if(textBox1.Text.Trim() == "")
            {
                MessageBox.Show("Missing value for persons name", "Error");
                textBox1.Focus();
                return;
            }

            // get the selected date value
            DateTime thisDate = monthCalendar1.SelectionStart;

            // Append current Time to allow for multiple dictionary key entries for this example
            string thisDateText = thisDate.ToString("MM/dd/yyyy " + DateTime.Now.ToString("hh:mm:ss"));

            // try and add the new date record
            try
            {
                if (radioButton1.Checked == true)
                {
                    // add this date to the birthDates dictionary
                    birthDates.Add(thisDateText, textBox1.Text.Trim());
                }
                else if(radioButton2.Checked == true)
                {
                    // add this date to the appointmentDates dictionary
                    appointmentDates.Add(thisDateText, textBox1.Text.Trim());
                }
            }
            catch (Exception ex)
            {
                // if error then display error message
                MessageBox.Show(ex.Message, "Error");
            }
            
            // reload the calendar to show this new date
            reloadCalendar();

            // display the records for this selected date
            displaySelectedDatesRecords();
        }

        private void loadAppointments()
        {
            // load non-repeating appointment dates from some data source
            // (to keep this example simple I am just adding them manually)
            appointmentDates.Add("01/15/2022", "Sales Tax Report");
            appointmentDates.Add("01/28/2022", "Dentist Appointment");
            appointmentDates.Add("02/26/2022", "Business Trip To Thailand");

        }

        private void loadBirthDates()
        {
            // load repeating birthdates from some data source
            // (to keep this example simple I am just adding them manually)
            birthDates.Add("01/04/1936", "Mom's Birthday");
            birthDates.Add("01/09/1913", "Richard Nixon");
            birthDates.Add("01/13/1985 04:24:45", "First Twins Birthday");
            birthDates.Add("01/13/1985 04:26:05", "Second Twins Birthday");
            birthDates.Add("02/06/1911", "Ronald Reagan");
            birthDates.Add("02/19/1934", "Dad's Birthday");
            birthDates.Add("05/29/1917", "John Kennedy");
            birthDates.Add("06/12/1924", "George H.W. Bush");
            birthDates.Add("06/14/1946", "Donald Trump");
            birthDates.Add("07/06/1946", "George W. Bush");
            birthDates.Add("07/14/1913", "Gerald Ford");
            birthDates.Add("08/04/1961", "Barack Obama");
            birthDates.Add("08/19/1946", "William Clinton");
            birthDates.Add("08/27/1908", "Lyndon Johnson");
            birthDates.Add("10/1/1924", "Jimmy Carter");
            birthDates.Add("11/20/1942", "Joe Biden");

        }
        
        private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
        {
            // display the records for this selected date
            displaySelectedDatesRecords();
        }

        private void reloadCalendar()
        {
            // suspend drawing the layout
            monthCalendar1.SuspendLayout();

            // remove all previously added birthdates
            monthCalendar1.RemoveAllAnnuallyBoldedDates();

            // add known birthdays
            foreach(KeyValuePair<string, string> thisBirthDay in birthDates)
            {
                monthCalendar1.AddAnnuallyBoldedDate(Convert.ToDateTime(thisBirthDay.Key));
            }

            // add known appointments
            foreach (KeyValuePair<string, string> thisAppointment in appointmentDates)
            {
                monthCalendar1.AddBoldedDate(Convert.ToDateTime(thisAppointment.Key));
            }

            // resume drawing the layout
            monthCalendar1.ResumeLayout();

            // update to ensure bolded dates are bold
            monthCalendar1.UpdateBoldedDates();
        }
		
    }
}

When you run the above example and interact with the MonthCalendar control object, and/or click on the New Button control object, then you should see something similar to the following:


example3

example4

example5

example6

example7

example8

example9

example10

Final Thoughts

Thank you for reading, I hope you found this blog post (tutorial) educational and helpful.


(0) pollYesResult
(0) pollNoResult



 
     About   |   Contact Us   |   Privacy   |   Terms & Conditions   |   © 2024 - T&J Divisions, LLC, All Rights Reserved