0
votes

Firstly my problem is something experimental rather than actual issue. My database table has a column of datetime which allows null value. There is just 1 record having null value at that column. Now after filling data into a DataTable using a data adapter (very basically) and show it on a DataGridView. I can see the cell having null value of datetime is empty (the underlying data contained in the DataTable is a DBNull). I have a DateTimePicker bound to the datetime field (which can have DBNull value). Now if I navigate the selection on DataGridView to the row having the null value at the datetime column I mentioned, the DateTimePicker (together with some other text fields) doesn't update the value (it looks like it stays at the previous selection). I also tried creating a Binding which formats the DBNull to such as DateTime.MinValue but nothing changes. Here is the code:

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);

The database table is just simple with some columns. I think the problem may be how DateTimePicker processes data. Without binding data to it, the controls show info OK corresponding to the current selection on DataGridView. This is the thing I hate the most when using Binding. It's very convenient but sometimes it is just impossible to understand and debug. If tracking the selection using event handler (the SelectionChanged event) and update the controls manually, this problem won't never be such time consuming.

I hope someone has experienced this issue and could give me some suggestion. Thank you.

1

1 Answers

0
votes

Well what I've done in fact should work however it is a little wrong here about formatting value for the DateTimePicker, the value should be in range MinDate and MaxDate. It did not throw any exception but if the row having null datetime column is the first row, right after binding an exception will be thrown and let me know everything wrong. Now the code can be like this:

binding.Format += (s,e) => {
  //debug shows that the execution can jump in here
  if(e.Value == DBNull.Value){
     e.Value = myDatePicker.MinDate;
  }
};