How to use MonthCalender to insert date in text box?

我的未来我决定 提交于 2019-11-30 00:00:38

问题


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?


回答1:


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.




回答2:


If you want to get Date from a month calender and display it in text box, then first of all drag and drop monthCalender from ToolBox in Visual Studio to your design form. and double click on it and write these code

  private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
    {
       textbox1.text = monthCalendar1.SelectionRange.Start.ToShortDateString();
    }

This will display a date like this 14/2/2014



来源:https://stackoverflow.com/questions/12852496/how-to-use-monthcalender-to-insert-date-in-text-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!