Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the background color of a DateTimePicker in .NET

In .NET (at least in the 2008 version, and maybe in 2005 as well), changing the BackColor property of a DateTimePicker has absolutely no affect on the appearance. How do I change the background color of the text area, not of the drop-down calendar?

Edit: I was talking about Windows forms, not ASP.

like image 415
Daniel H Avatar asked Oct 13 '08 18:10

Daniel H


People also ask

How do I change Backcolor in C#?

To change the background color of text in Console, use the Console. BackgroundColor Property in C#.

What is DateTimePicker C#?

A DateTimePicker control allows users to select a date and time in Windows Forms applications.


1 Answers

According to MSDN :

Setting the BackColor has no effect on the appearance of the DateTimePicker.

You need to write a custom control that extends DateTimePicker. Override the BackColor property and the WndProc method.

Whenever you change the BackColor, don't forget to call the myDTPicker.Invalidate() method. This will force the control to redrawn using the new color specified.

const int WM_ERASEBKGND = 0x14;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
    if(m.Msg == WM_ERASEBKGND)
    {
        using(var g = Graphics.FromHdc(m.WParam))
        {
            using(var b = new SolidBrush(_backColor))
            {
                g.FillRectangle(b, ClientRectangle);
            }
        }
        return;
    }

    base.WndProc(ref m);
}
like image 83
Vivek Avatar answered Sep 19 '22 15:09

Vivek