How to Add DateTimePicker Column Using C#

Here’s another tutorial that beginners in programming will find it very useful when they are writing codes. In this tutorial, I’m going to teach you how to add DateTimePicker Column using C#. This is just a simple method that can view the datetimepicker in a column and select the date that you need. Just follow the guide below and you will see how it works.

Creating Application

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application for c#. ps1

Step 2

Do the form just like shown below. ps2

Step 3

Press F7 to open the code editor. In the code editor, instantiate the object that is needed.
  1.    
  2.         DateTimePicker datePicker = new DateTimePicker();

Step 4

Click the DataGridView and go to the properties. In the properties, hit the event just like a lightning bolt. Scroll down and double click the event which is dtg_Date_CellClick to open the code editor. ps3

Step 5

In the code editor, write the following codes to create a DateTimePicker column when the cell is clicked.
  1.    
  2.         private void dtg_Date_CellClick(object sender, DataGridViewCellEventArgs e)
  3.         {
  4.             if (e.ColumnIndex == 0)
  5.             {
  6.                 datePicker = new DateTimePicker();
  7.                 dtg_Date.Controls.Add(datePicker);
  8.                 datePicker.Format = DateTimePickerFormat.Short;
  9.  
  10.                 Rectangle Rectangle = dtg_Date.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
  11.                 datePicker.Size = new Size(Rectangle.Width, Rectangle.Height);
  12.                 datePicker.Location = new Point(Rectangle.X, Rectangle.Y);
  13.  
  14.                 datePicker.CloseUp += new EventHandler(datePicker_CloseUp);
  15.                 datePicker.TextChanged += new EventHandler(datePicker_OnTextChange);
  16.  
  17.  
  18.                 datePicker.Visible = true;
  19.             }
  20.         }

Step 6

Write the following codes for the textChange event of the DateTimePicker.
  1.    
  2.         private void datePicker_OnTextChange(object sender, EventArgs e)
  3.         {
  4.  
  5.             dtg_Date.CurrentCell.Value = datePicker.Text.ToString();
  6.         }

Step 7

Write the following codes for the closeUp event of the DateTimePicker.
  1.    
  2.         void datePicker_CloseUp(object sender, EventArgs e)
  3.         {
  4.             datePicker.Visible = false;
  5.         }
The complete source code is included. You can download it and run it on your computer. For any questions about this article. You can contact me @ Email – [email protected] Mobile No. – 09305235027 – TNT Or feel free to comment below.

Add new comment