首先,我的问题是一些实验性的问题,而不是实际的问题。我的数据库表有一个datetime
列,它允许空值。在该列中只有1条记录具有空值。现在,在使用数据适配器(基本上)将数据填充到DataTable
并在DataGridView上显示数据之后。我可以看到具有null值的日期时间的单元格是空的( DataTable中包含的底层数据是一个DBNull
)。我有一个绑定到datetime字段的DateTimePicker (它可以有DBNull值)。现在,如果我将DataGridView上的选择导航到在我提到的datetime列中具有空值的行,则DateTimePicker (以及其他一些文本字段)不会更新该值(看起来它停留在前面的选择中)。我还尝试创建一个Binding
,它将DBNull
格式化为DateTime.MinValue
,但是没有任何改变。以下是代码:
var dt = new DataTable();
myAdapter.Fill(dt);
dataGridView.DataSource = dt;
//bind controls
var binding = new Binding("Value", dataGridView.DataSource, "birthdate");
//here is what I tried to convert DBNull.Value to DateTime.MinValue
binding.Format += (s,e) => {
//debug shows that the execution can jump in here
if(e.Value == DBNull.Value){
e.Value = DateTime.MinValue;
}
};
myDatePicker.DataBindings.Add(binding);
对于某些列,数据库表非常简单。我认为问题可能在于DateTimePicker如何处理数据。如果没有绑定数据,控件将显示与DataGridView上当前选择对应的信息OK。这是我在使用绑定时最讨厌的东西。它非常方便,但有时只是不可能理解和调试。如果使用事件处理程序( SelectionChanged事件)跟踪所选内容并手动更新控件,那么这个问题就不会那么费时。
我希望有人经历过这个问题,并能给我一些建议。谢谢。
发布于 2015-07-31 01:04:21
实际上,我所做的应该是有效的,但是对于DateTimePicker
的格式化值来说,这里有点错误,值应该在MinDate
和MaxDate
的范围内。它没有抛出任何异常,但是如果具有null datetime列的行是第一行,那么在绑定之后就会抛出异常,并让我知道所有错误。现在代码可以如下所示:
binding.Format += (s,e) => {
//debug shows that the execution can jump in here
if(e.Value == DBNull.Value){
e.Value = myDatePicker.MinDate;
}
};
https://stackoverflow.com/questions/31740066
复制