Datatimepicker Nullable

Posted by Murugavelmsc under C# on 9/4/2013 | Points: 10 | Views : 1069 | Status : [Member] | Replies : 1
Hi Expert,

I have developing a window application with datepicker as (UI component).
In this, i select the date and update means it does not insert into db. But select in the second time it gets updated in db.
First time it retrieve null values only
second time retrieve the date and gets updated in db

Please help me out on this.

UI Componenet
using System;
using System.Windows.Forms;

namespace UIComponent
{
/// <summary>
/// Summary description for DateTimePicker.
/// </summary>
public class DateTimePicker : System.Windows.Forms.DateTimePicker
{
private DateTimePickerFormat oldFormat = DateTimePickerFormat.Long;

private string oldCustomFormat = null;
private bool bIsNull = false;



public DateTimePicker()
: base()
{

}
public new DateTime Value
{
get
{
if (bIsNull)
return this.MinDate;
else
return base.Value;
}
set
{
if (value == this.MinDate)
{
if (bIsNull == false)
{
oldFormat = this.Format;
oldCustomFormat = this.CustomFormat;
bIsNull = true;
}

this.Format = DateTimePickerFormat.Custom;
this.CustomFormat = " ";
}
else
{
if (bIsNull)
{
this.Format = oldFormat;
this.CustomFormat = oldCustomFormat;
bIsNull = false;
}
base.Value = value;
}
}
}
public void SetToNullValue()
{
Value = this.MinDate;
}
protected override void OnCloseUp(EventArgs eventargs)
{
if (Control.MouseButtons == MouseButtons.None)
{
if (bIsNull)
{
this.Format = oldFormat;
this.CustomFormat = oldCustomFormat;
bIsNull = false;
}
}
base.OnCloseUp(eventargs);
}

protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);

if (e.KeyCode == Keys.Delete)
this.Value = this.MinDate;
}
}
}

Regards,
Murugavel S
murugavel.sadagopan@gmail.com
http://murugavelmsc.blogspot.in/



Responses

Posted by: Bandi on: 9/4/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
DateTimePickers can't be set to null because DateTime can't be null, but you can set them to DateTime.MinValue which is the default value for an uninitialized DateTime. And then you just check if the dtp.Value = DateTime.MinValue and if so, treat it as null.

However, if you want to really distinguish when no value has been selected, the easiest way is to set DateTimePicker.ShowCheckBox to true, and then you check dtp.Checked and if it's true, you read the value, otherwise you treat it as a null.

Refer http://stackoverflow.com/questions/2983563/how-to-set-datetimepicker-with-null-value-if-date-not-selectedc-winforms
http://stackoverflow.com/questions/9860847/setting-the-date-time-picker-to-blank-or-0-value

Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

Murugavelmsc, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response