In my Windows Form Application written in C#, I have a DateTimePicker
control. I want to center the text part of the control, but is it possible?
My current one has its text at the left, giving a lot of space on the right side.
I tried
myDateTimePicker.TextAlign = ContentAlignment.MiddleCenter;
but it gave the error:
'System.Windows.Forms.DateTimePicker' does not contain a definition for 'TextAlign' and no extension method 'TextAlign' accepting a first argument of type 'System.Windows.Forms.DateTimePicker' could be found (are you missing a using directive or an assembly reference?)
I could not find any property that seemed to work, and I could not find the solution anywhere on the Internet either. Is this not possible at all?
You can always override the OnPaint
handler by subclassing DateTimePicker
:
public class CenteredDateTimePicker : DateTimePicker
{
public CenteredDateTimePicker()
{
SetStyle(ControlStyles.UserPaint, true);
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), ClientRectangle, new StringFormat
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
});
}
}
However, the scrollbar is not drawn here, so you might have to improvise somehow...
Unfortunately, you can't find the definition of DateTimePicker.OnPaint
on Reference Source.