3

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.

enter image description here

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?

H H
  • 263,252
  • 30
  • 330
  • 514
J.Doe
  • 329
  • 3
  • 14
  • It likely impossible to do in old WinForms. Consider switching to WPF where you can style/customize the controls. – Xiaoy312 Oct 10 '17 at 20:17
  • 3
    It's always possible... but not always simple. For example, you could override the OnPaint handler, but since you can't rely on the base Paint, that leaves you to draw everything, in any circumstance. – Joel Coehoorn Oct 10 '17 at 20:18

2 Answers2

6

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.

Xiaoy312
  • 14,292
  • 1
  • 32
  • 44
0

A simple but not very elegent solution is to add white spaces in your Custom format property however, if your datetimepicker size is dynamic it will not adjust accordingly.

Ayhan
  • 1
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 20 '21 at 11:04