How can I display the MonthCalendar
on top similar to the DateTimePicker
drop down? I have a
a custom control (TextBox
and Button
) that displays the MonthCalendar
dynamically when clicked.
I was able to get it in front of the controls with the panel but not over the panel. Image below;
private void btn_Click(object sender, EventArgs e)
{
if (mc.Parent == null)
{
this.Parent.Controls.Add(mc);
mc.Location = new Point(this.Location.X, this.Location.Y this.Height);
mc.BringToFront();
}
else
{
mc.Show();
}
}
CodePudding user response:
The drop-down calendar on a DateTimePicker
is a floating window, as is the drop-down list on a ComboBox
. The MonthCalendar
is just a regular control so, just like any other control, it cannot be displayed outside the bounds of its parent. If you want it displayed over a form and outside the bounds of a Panel
then you'd need to make its parent the form, rather than the Panel
. If you want it to be displayed outside the bounds of the form too then you'd need to create a new, borderless form and make that the control's parent.
Here is a method you can use to move a child control from one parent to another without changing its absolute position on screen:
/// <summary>
/// Moves a child control from its current parent to a new parent while maintaining the same absolute location.
/// </summary>
/// <param name="child">
/// The child control to move.
/// </param>
/// <param name="newParent">
/// The new parent to move the child control to.
/// </param>
private void ChangeParent(Control child, Control newParent)
{
var screenLocation = child.PointToScreen(Point.Empty);
child.Parent = null;
child.Location = newParent.PointToClient(screenLocation);
child.Parent = newParent;
}
In your case, you probably want to call that like so:
ChangeParent(mc, this);
You may need to call BringToFront
on the child control afterwards, depending on your z-order.
Note that you can also just add the MonthCalendar
to the form in the designer and then change its Location
in the properties window to get it in the right place.