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

namespace DateBoxApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // leaving DateBox
        private void ftbDate_Leave(object sender, EventArgs e)
        {
            // if focus did not shift to Calendar dropdown
            // close Calendar dropdown on losing focus
            if (!monthCalendar.Focused)
                monthCalendar.Visible = false;
        }

        // validate Date in DateBox
        private void ftbDate_Validating(object sender, CancelEventArgs e)
        {
            DateTime outdate;
            if (ftbDate.Text != "") // no validation on empty text
            {
                // if can't validate date
                if (!DateTime.TryParse(ftbDate.Text, out outdate))
                {
                    picError.Visible = true; // show error icon
                    if (!monthCalendar.Focused)
                        e.Cancel = true; // set Cancel if trying to
                                         // leave DateBox 
                }
            }
        }

        // Date is valid
        private void ftbDate_Validated(object sender, EventArgs e)
        {
            picError.Visible = false; // remove error icon
        }

        // Calendar date selected
        private void monthCalendar_DateSelected(object sender, DateRangeEventArgs e)
        {
            // set DateBox text to selected date
            ftbDate.Text = e.Start.ToShortDateString();
            ftbDate.Focus(); // focus DateBox
            monthCalendar.Visible = false; // close Calendar dropdown
        }

        // click on dropdown icon
        private void picCalendar_Click(object sender, EventArgs e)
        {
            // flip Calendar dropdown
            monthCalendar.Visible = !monthCalendar.Visible;
            ftbDate.Focus(); // focus datebox
        }
    }
}