I have a datetimepicker that I bind to the Date / Time null column in the dataset. I have successfully applied the Format event to null, not null. But, when I remove the dtp control, it does not get null in the dataset. This is my code:
dtpBirthdate.DataBindings.Add(new Binding("Value", bsStaff, "birthDate", true)); dtpBirthdate.DataBindings["Value"].Format += new ConvertEventHandler(dtpFormat); dtpBirthdate.DataBindings["Value"].Parse += new ConvertEventHandler(dtpParse);
Formatting and parsing events:
private void dtpFormat(object sender, ConvertEventArgs e) { Binding b = sender as Binding; if(b != null) { DateTimePicker dtp = (b.Control as DateTimePicker); if(dtp != null) { if (e.Value == null || e.Value == DBNull.Value) { dtp.Checked = false; dtp.CustomFormat = " "; e.Value = false; } else { dtp.Checked = true; dtp.CustomFormat = "dd-MMM-yyyy"; dtp.Value = (DateTime) e.Value; } } } } private void dtpParse(object sender, ConvertEventArgs e) { Binding b = sender as Binding; if (b != null) { DateTimePicker dtp = (b.Control as DateTimePicker); if (dtp != null) { if (dtp.Checked == false) { e.Value = DBNull.Value; } else { e.Value = dtp.Value; } } } }
After debugging, I found that it goes into an endless loop between parsing and formatting events. What is wrong with my code?
Edit: There is also a datagridview bound to the bsStaff binding source.
c # parsing nullable binding datetimepicker
Hilal al-rajhi
source share