NULL Values with DateTimePicker control

L

LS

I found this on a search from Google which is exactly what I am looking for.
However, when I add the code to my window, I get a runtime error stating
that a TypeCast error from Boolean to DateTime when the Formatter event is
being created.

myDtPicker.DataBindings["Checked"].Format
+= new ConvertEventHandler(Formatter);

Thanks,

Larry

**Message I found from a Google Search**

Okay folks, I think I have a work around for data binding a
DateTimePicker to a column that allows nulls. I've spent a lot of
time on this, and this is the only thing I've come up with that works
the way we'd all expect:

Bind to the "Checked" field only, with something like this:

myDtPicker.DataBindings.Add(
new Binding("Checked", myDs, "table.dateColumn"));

Then add a formatter and parser to the binding:

myDtPicker.DataBindings["Checked"].Format
+= new ConvertEventHandler(Formatter);
myDtPicker.DataBindings["Checked"].Parse
+= new ConvertEventHandler(Parser);

Then Formatter and Parse look like this:

private void Formatter(object source, ConvertEventArgs e) {
Binding binding = source as Binding;
DateTimePicker dtp = binding.Control as DateTimePicker;
if(dtp == null)
return;
if(e.Value==null || e.Value==DBNull.Value) {
dtp.Value = DateTime.Now; // optional
e.Value = false;
} else {
dtp.Value = (DateTime) e.Value;
e.Value = true;
}
}

private void Parser(object source, ConvertEventArgs e) {
Binding binding = source as Binding;
DateTimePicker dtp = binding.Control as DateTimePicker;
if(dtp == null)
return;
if(dtp.Checked)
e.Value = dtp.Value;
else
e.Value = DBNull.Value;
}

Be glad to hear if this works for you.

Jason Pettys
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top