C# DateTimePicker DataBinding Parse event not working
I have a datetimepicker that I am binding with nullable Date/Time column in dataset. I applied Format event successfully for null and not null object value. But, when I uncheck dtp control it does not get set to 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);
Format and Parse 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 to infinite loop between parse and format events. What is wrong with my code?
Edit: There is also a datagridview binded to bsStaff bindingsource.
You are casting "Binding b = sender as Binding" before the null check. check if the sender is null before casting and you should be fine.
I noticed that you are using a Databinding event capture for both controls but on your first dtpFormat event handler you don't check for databinding values first.
Imho this line of code:
if (e.Value == null || e.Value == DBNull.Value)
needs to be changed to
if (e.Value == DBNull.Value || e.Value == null)
The issue is you need to set e.Value to something; but if you change it, it will fire parse again. Try setting it to it's original value.
e.Value = dtp.Value;
Here is a link to someone who has ran into this before. They were not using your DbNull.Value, but other than that it is nearly identical to what you are doing.
http://blogs.interknowlogy.com/2007/01/21/winforms-databinding-datetimepicker-to-a-nullable-type/
链接地址: http://www.djcxy.com/p/95826.html上一篇: 比较swift中的文字类型失败?