Search code examples
c#.netc++-climonthcalendar

How to use MonthCalender to insert date in text box?


I have a textBox1 in my windows form. I would like to use it to get date from the user. I want to show MonthCalender1 once the user put the cursor in the textbox1 and then set the date in the textbox1 automatically and then the calender will disappear. How can I use C# or C++/CLI to do that?


Solution

  • This is not the best code, but I hope you get the idea:

    public Form1()
    {
        InitializeComponent();
        monthCalendar1.MaxSelectionCount = 1;
    }
    
    private void textBox1_Enter(object sender, EventArgs e)
    {
        monthCalendar1.Visible = true;
    }
    
    private void textBox1_Leave(object sender, EventArgs e)
    {
        if (!monthCalendar1.Focused)
            monthCalendar1.Visible = false;
    }
    
    private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
    {
        var monthCalendar = sender as MonthCalendar;
        textBox1.Text = monthCalendar.SelectionStart.ToString();
    }
    
    private void monthCalendar1_Leave(object sender, EventArgs e)
    {
        var monthCalendar = sender as MonthCalendar;
        monthCalendar.Visible = false;
    }
    

    First, you set the MaxSelectionCount for you monthCalendar control. Next, you adding event listeners for leaving focus and gaining focus. If you don't get it working, I can provide sample solution where I tested it.