DateTimePicker and DBNull
You can’t bind a Windows Forms DateTimePicker to a field
that might contain DBNull… so I did this;
public class
DBDateTimePicker:DateTimePicker
{
public
DBDateTimePicker()
{
//
// TODO: Add constructor logic
here
//
}
public object DBValue
{
get
{
if (this.Checked)
return base.Value;
else
return
System.DBNull.Value;
}
set
{
if (System.Convert.IsDBNull(value))
this.Checked=false;
else
this.Value = Convert.ToDateTime(value);
}
}
}
Then I bind to “DBValue” (instead of Value) and it appears to
work fine… if it is null, it is unchecked and disabled, otherwise it is enabled
and can be set to any normal date value... if you uncheck the box yourself, then
the data field is set to DBNull...
Not sure if it the best idea, but I can’t override Value so this
seems like a reasonable alternative… of course, I never looked around for the
"official" solution or any other possible answers, so let me know if you have a
better idea!
Comments
- Anonymous
February 28, 2003
Another little code snippet : Code/Tea/Etc... - Anonymous
June 06, 2003
This is what I found as well.. but I got into a pickle, because for some unknown reason, binding to this ALWAYS makes it flag the DataRow as modified, so using HasChanges() will ALWAYS return true!.. I wanted to know if the user changed anything so I can prompt them about saving before exiting, so I found this variation to work (FINALLY!):
public class DbDateTimePicker : System.Windows.Forms.DateTimePicker
{
public DbDateTimePicker()
{
}
[Bindable(true), Browsable(false)]
public new object Value
{
get
{
if (Checked) return base.Value;
else return DBNull.Value;
}
set
{
if (Convert.IsDBNull(value)) this.Checked = false;
else base.Value = Convert.ToDateTime(value);
}
}
} - Anonymous
March 01, 2004
both of your solution dont' seem to work for me. the db value did get binded, but won't unchecked when value is dbnull. - Anonymous
March 01, 2004
The comment has been removed - Anonymous
March 01, 2004
Thanks Kevin, I'll have to try that... it is odd that it was necessary though, since I am using that control without any issues in my applications already. Perhaps there is some other difference in how I am binding and handling changes that avoids this problem? - Anonymous
March 25, 2004
Just bind to DateTimePicker.Text and it will work; If DBNull is autoconverted to DateTime.Now;
;) - Anonymous
April 10, 2004
The comment has been removed - Anonymous
May 26, 2004
The comment has been removed