Click here to Skip to main content
Licence CPOL
First Posted 17 Aug 2009
Views 35,069
Downloads 3,476
Bookmarked 36 times

Nullable datetime column in .NET DataGrid with DateTimePicker

By | 17 Aug 2009 | Article
A nullable datetime column in .NET DataGrid with DateTimePicker.
 
Part of The SQL Zone sponsored by
See Also

Introduction

I have always known a lot of people who have problems with the standard .NET 2.0 DataGridView and the nullable DateTime column (created with Oracle PL/SQL column definition):

dtReceived DATE

or a MS SQL Server DateTime column with NULL values in Transact SQL:

dtReceived DATETIME NULL

Google Search normally gives this Microsoft sample for calendar columns: How to: Host Controls in Windows Forms DataGridView Cells. This is a good start point, but it isn't enough. You can never correctly fill DateTime DataGridView cells with NULL. I found many variants for the simple DateTimePicker class, but work samples absent for nullable DateTime columns in a DataGridView.

Solution

I spent a lot of time on the Internet searching, and found a nice article about a nullable DateTimePicker: DateTimePicker DBNull. I then made several corrections and as 'magic touch', and it works for DataGridViews now.

Using the code

These are the steps we need:

  1. Rename the class DateTimePicker to DatePicker (the same name for different classes is a bad practice, in my opinion):
  2. public class DatePicker : System.Windows.Forms.DateTimePicker
    {..
  3. Add the following code snippet to the DatePicker class:
  4. public string ToShortDateString() 
    { 
        if (!realDate) 
            return String.Empty; 
        else 
        { 
            DateTime dt = (DateTime)Value; 
            return dt.ToShortDateString(); 
        }
    }
  5. Correct CalendarEditingControl.cs from the Microsoft Sample for usage in our DatePicker:
  6. class CalendarEditingControl : DatePicker, IDataGridViewEditingControl { ...
  7. Correct CalendarCell.cs from the Microsoft Sample for DBNull:
  8. public override void InitializeEditingControl(int rowIndex, object 
    initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle) 
    { 
        // Set the value of the editing control to the current cell value.
        base.InitializeEditingControl(rowIndex, initialFormattedValue, 
                                                dataGridViewCellStyle); 
        CalendarEditingControl ctl = 
        DataGridView.EditingControl as CalendarEditingControl;
    
        // ++ vic 14-aug-2009
         object val = null;
         try 
         {
              val = this.Value;
         }
         catch (Exception ex)
         { 
              // Argument ot of range (value doesn't exists in collection)
              return;
         }
         
         if (val != System.DBNull.Value)
              ctl.Value = (DateTime)val;
    }

That's all, folks :)

You should press the DEL key to set a NULL filled DateTime cell.

The source code is attached. You can directly use the files from my project in your projects like in the Microsoft Samples (DatePicker.cs, CalendarCell.cs, CalendarColumn.cs, CalendarEditingControl.cs):

private void Form1_Load(object sender, EventArgs e)
{
     CalendarColumn col = new CalendarColumn();
     this.dataGridView1.Columns.Add(col);
     this.dataGridView1.RowCount = 5;
     foreach (DataGridViewRow row in this.dataGridView1.Rows)
     {
          row.Cells[0].Value = DateTime.Now;
     }
}

or from the Microsoft Visual Studio Data Designer for DataGrid (right mouse click on DataGridView, and choose 'Edit columns' from the context menu):

I have attached a real sample with database (Visual Studio 2008 / SQL Express database).

History

  • 14-Aug-2009: Initial version posted.
  • 16-Aug-2009: Database sample added.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

vic_ch2000

Web Developer

Russian Federation Russian Federation

Member

Microsoft certified professional developer (MCPD)

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionReallly good article! Pinmembervishme0:12 27 Mar '12  
Questiondoubt! Pinmemberchoosechrist21:14 26 Feb '12  
BugRow delete problem PinmemberMember 81712966:38 18 Nov '11  
QuestionSome bug... Pinmemberdomivan4:37 24 Aug '11  
GeneralBrilliant! Thanks so much PinmemberDaniel Neal0:46 12 May '11  
Generalediting problem. PinmemberMohsin Hawra22:22 14 Jul '10  
GeneralRe: editing problem. PinmemberRazze2:07 11 Oct '10  
AnswerRe: editing problem. Pinmembercje12316:41 5 Dec '10  
GeneralGreat job Pinmemberkhalil Youssef21:14 30 Jun '10  
GeneralGreat Job PinmemberMohammad Rafi Bin Abd Alim20:11 16 Jun '10  
QuestionAllowing editing of the 'Time' portion of the DateTime [modified] PinmemberKMalone22:00 11 May '10  
AnswerRe: Allowing editing of the 'Time' portion of the DateTime PinmemberKMalone23:54 11 May '10  
GeneralRe: Allowing editing of the 'Time' portion of the DateTime PinmemberKim Bilida5:58 16 Jul '10  
GeneralGreat! PinmemberMember 411002512:05 20 Mar '10  
Generalthis.Value VS this.ToShortDateString() PinmemberDrew Loika11:38 1 Feb '10  
GeneralRe: this.Value VS this.ToShortDateString() Pinmembervic_ch200018:23 1 Feb '10  
Generalthank you PinmemberSamir the Boy0:06 13 Jan '10  
GeneralDBNull vs null PinmemberDrew Loika13:09 17 Dec '09  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 17 Aug 2009
Article Copyright 2009 by vic_ch2000
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid