Monday 2 October 2006

Winforms DateTime Databinding

ScottWinforms and databinding has significantly improved in .NET 2.0 and a line of code such as - txtName.DataBindings.Add("Text", DataObject, "ClientName"); - just works with both data and nulls :)

However, the DateTimePicker and its ability to handle nulls is not quite a simple. To handle nulls with the DateTimePicker a few extra lines of code is needed.

The format property of the DateTimePicker control needs to be set. I have chosen Custom and as such the custom format is also set.
dtpAppointment.Format = DateTimePickerFormat.Custom;
dtpAppointment.CustomFormat = "dd/MMM/yyyy HH:mm";


This next line is really the most crucial. Notice the only difference with the simple single data binding line above is now there is a true paramater at the end. This is the formattingEnabled argument and without formattingEnabled set to true the handling of nulls just does not work!!!
dtpAppointment.DataBindings.Add("Value", DataObject, "AppointmentDate", true);

Happy binding :)

No comments: