More Windows forms stuff. I don’t like really complex Web forms controls ‘cos sometimes they seem a bit flakey – but I’m beginning to wonder if Windows Forms stuff is any better.
Two problems with the DateTimePicker. First, it can’t have a null value. What? You might not want to have a value in it? That’s craaazzzy! Inconceivable! What do you mean that your database tables allow null values in a DateTime column?
All you can do is set ShowCheckbox to ‘true’. This will give you a little checkbox, to turn on or off the editing of the value. You could then wrap the DateTimePicker, and return yourself null if the ‘Checked’ value is false.
Secondly, it has no BackColor property, so I couldn’t colour it pink when the field was invalid, meaning it had to have a value – therefore, the checkbox mentioned above has to be ‘Checked’. I managed to get around this by subclassing the DateTimePicker – but had some problems when you then focussed on it to try to edit it. My solution (below) was to turn off any background colour during editing…
private bool _hasFocus = false;
private Color _originalColor;
public override Color BackColor
{
get
{
return base.BackColor;
}
set
{
base.BackColor = value;
Invalidate();
}
}
protected override void OnGotFocus(EventArgs e)
{
if (this.BackColor != Color.Pink)
{
_originalColor = this.BackColor;
}
this.BackColor = Color.White;
_hasFocus = true;
base.OnGotFocus(e);
}
protected override void OnLostFocus(EventArgs e)
{
_hasFocus = false;
if (this.isValid)
{
this.BackColor = _originalColor;
}
else
{
this.BackColor = Color.Pink;
}
base.OnLostFocus(e);
}
protected override void WndProc(ref Message m)
{
if ((!_hasFocus) && (m.Msg == 20))
{
Graphics g = Graphics.FromHwnd(m.HWnd);
g.FillRectangle(new SolidBrush(this.BackColor), this.ClientRectangle);
g.Dispose();
return;
}
base.WndProc(ref m);
}
Hey, that was interesting,
it is a good excercise to learn more about c#
Thanks