问题
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