473,732 Members | 2,210 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem in datagridview datetimepicker column.

88 New Member
I'm trying to make a datagridview column to act like a datetimepicker column (C#.Net 2005). These are the behaviours that the dgv should have:
1) Initially all the cells of the dtp column should be blank unless they are filled by the user.
2) As soon as the user enters a cell, the dtp control should appear as the editing control of that cell. If there's a value in the cell beforehand, that value is set as the value of the dtp editing control and it is checked, else the dtp editing control remains unchecked.
3) If the user selects a date from the dtp editing control and moves to another cell the value of the dtp should be set to the previous cell in string format (In that way we can define custom format for the cell e.g. dd MMM yyyy).
4) If the user unchecks the dtp editing control while it's on a cell the value of that cell should be set to null irrespective of whether the cell had a value beforehand.

I managed everything till point 3. But can't work out with point 4. Cannot set the value of a cell to null when its dtp editing control is unchecked. There's a way to do it by handling the Datagridview_Ce llValidating event. But in that case if the datagridview is data bound, u need to uncheck the editing control once, goto another cell, come back to the previous one and uncheck it once again to set its cell value to null. I want to know if there's any way to do it through the derived classes or their class template that I'm using so that I wont have to use that event and everything can be done through the class template only. Please help. My code follows:

Code for the template (I'm using a code file) containing all the derived classes:
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Windows.Forms;
  3.  
  4. namespace DGV_DateTimePicker
  5. {
  6.     public class DateTimePickerColumn : DataGridViewColumn
  7.     {
  8.         public DateTimePickerColumn()
  9.             : base(new DateTimePickerCell())
  10.         {
  11.         }
  12.  
  13.         public override DataGridViewCell CellTemplate
  14.         {
  15.             get
  16.             {
  17.                 return base.CellTemplate;
  18.             }
  19.             set
  20.             {
  21.                 // Ensure that the cell used for the template is a DateTimePickerCell.
  22.                 if (value != null &&
  23.                     !value.GetType().IsAssignableFrom(typeof(DateTimePickerCell)))
  24.                 {
  25.                     throw new InvalidCastException("Must be a DateTimePickerCell");
  26.                 }
  27.                 base.CellTemplate = value;
  28.             }
  29.         }
  30.     }
  31.  
  32.     public class DateTimePickerCell : DataGridViewTextBoxCell
  33.     {
  34.  
  35.         public DateTimePickerCell()
  36.             : base()
  37.         {
  38.             // Use the custom defined date format.
  39.             this.Style.Format = "dd MMM yyyy";
  40.         }
  41.  
  42.         public override void InitializeEditingControl(int rowIndex, object
  43.             initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
  44.         {
  45.             // Set the value of the editing control to the current cell value.
  46.             base.InitializeEditingControl(rowIndex, initialFormattedValue,
  47.                 dataGridViewCellStyle);
  48.  
  49.             DateTimePickerEditingControl ctl = (DateTimePickerEditingControl)DataGridView.EditingControl;
  50.             DateTime d;
  51.             ctl.Value = DateTime.TryParse((Value ?? "").ToString(), out d) ? d : DateTime.Now;
  52.  
  53.             /*Check whether the datagridview is databound/unbound. In both cases if the value of the cell
  54.          isn't null then check the DateTimePickerEditing Control else uncheck it.*/
  55.             if (ctl.EditingControlDataGridView.CurrentCell.OwningColumn.IsDataBound)
  56.                 ctl.Checked = Value.ToString() == "" ? false : Value == null ? false : true;
  57.             else
  58.                 ctl.Checked = Value == null ? false : true;
  59.         }
  60.  
  61.         public override Type EditType
  62.         {
  63.             get
  64.             {
  65.                 // Return the type of the editing contol that DateTimePickerCell uses.
  66.                 return typeof(DateTimePickerEditingControl);
  67.             }
  68.         }
  69.  
  70.         public override Type ValueType
  71.         {
  72.             get
  73.             {
  74.                 // Return the type of the value that DateTimePickerCell contains.
  75.                 return typeof(DateTime);
  76.             }
  77.         }
  78.  
  79.         public override object DefaultNewRowValue
  80.         {
  81.             get
  82.             {
  83.                 //Return null as the default value for new row.
  84.                 return null;
  85.             }
  86.         }
  87.     }
  88.  
  89.     class DateTimePickerEditingControl : DateTimePicker, IDataGridViewEditingControl
  90.     {
  91.         DataGridView dataGridView;
  92.         private bool valueChanged = false;
  93.         int rowIndex;
  94.  
  95.         public DateTimePickerEditingControl()
  96.         {
  97.             this.Format = DateTimePickerFormat.Custom;
  98.             this.CustomFormat = "dd MMM yyyy";
  99.             this.ShowCheckBox = true;
  100.             this.Checked = false;
  101.         }
  102.  
  103.         // Implements the IDataGridViewEditingControl.EditingControlFormattedValue 
  104.         // property.
  105.         public object EditingControlFormattedValue
  106.         {
  107.             get
  108.             {
  109.                 return this.Value.ToShortDateString();
  110.             }
  111.             set
  112.             {
  113.                 if (value is String)
  114.                 {
  115.                     this.Value = DateTime.Parse((String)value);
  116.                 }
  117.             }
  118.         }
  119.  
  120.         // Implements the 
  121.         // IDataGridViewEditingControl.GetEditingControlFormattedValue method.
  122.         public object GetEditingControlFormattedValue(
  123.             DataGridViewDataErrorContexts context)
  124.         {
  125.             return EditingControlFormattedValue;
  126.         }
  127.  
  128.         // Implements the 
  129.         // IDataGridViewEditingControl.ApplyCellStyleToEditingControl method.
  130.         public void ApplyCellStyleToEditingControl(
  131.             DataGridViewCellStyle dataGridViewCellStyle)
  132.         {
  133.             this.Font = dataGridViewCellStyle.Font;
  134.             this.CalendarForeColor = dataGridViewCellStyle.ForeColor;
  135.             this.CalendarMonthBackground = dataGridViewCellStyle.BackColor;
  136.         }
  137.  
  138.         // Implements the IDataGridViewEditingControl.EditingControlRowIndex 
  139.         // property.
  140.         public int EditingControlRowIndex
  141.         {
  142.             get
  143.             {
  144.                 return rowIndex;
  145.             }
  146.             set
  147.             {
  148.                 rowIndex = value;
  149.             }
  150.         }
  151.  
  152.         // Implements the IDataGridViewEditingControl.EditingControlWantsInputKey 
  153.         // method.
  154.         public bool EditingControlWantsInputKey(
  155.             Keys key, bool dataGridViewWantsInputKey)
  156.         {
  157.             // Let the DateTimePicker handle the keys listed.
  158.             switch (key & Keys.KeyCode)
  159.             {
  160.                 case Keys.Left:
  161.                 case Keys.Up:
  162.                 case Keys.Down:
  163.                 case Keys.Right:
  164.                 case Keys.Home:
  165.                 case Keys.End:
  166.                 case Keys.PageDown:
  167.                 case Keys.PageUp:
  168.                     return true;
  169.                 default:
  170.                     return !dataGridViewWantsInputKey;
  171.             }
  172.         }
  173.  
  174.         // Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit 
  175.         // method.
  176.         public void PrepareEditingControlForEdit(bool selectAll)
  177.         {
  178.             // No preparation needs to be done.
  179.         }
  180.  
  181.         // Implements the IDataGridViewEditingControl
  182.         // .RepositionEditingControlOnValueChange property.
  183.         public bool RepositionEditingControlOnValueChange
  184.         {
  185.             get
  186.             {
  187.                 return false;
  188.             }
  189.         }
  190.  
  191.         // Implements the IDataGridViewEditingControl
  192.         // .EditingControlDataGridView property.
  193.         public DataGridView EditingControlDataGridView
  194.         {
  195.             get
  196.             {
  197.                 return dataGridView;
  198.             }
  199.             set
  200.             {
  201.                 dataGridView = value;
  202.             }
  203.         }
  204.  
  205.         // Implements the IDataGridViewEditingControl
  206.         // .EditingControlValueChanged property.
  207.         public bool EditingControlValueChanged
  208.         {
  209.             get
  210.             {
  211.                 return valueChanged;
  212.             }
  213.             set
  214.             {
  215.                 valueChanged = value;
  216.             }
  217.         }
  218.  
  219.         // Implements the IDataGridViewEditingControl
  220.         // .EditingPanelCursor property.
  221.         public Cursor EditingPanelCursor
  222.         {
  223.             get
  224.             {
  225.                 return base.Cursor;
  226.             }
  227.         }
  228.  
  229.         protected override void OnValueChanged(EventArgs eventargs)
  230.         {
  231.             // Notify the DataGridView that the contents of the cell
  232.             // have changed.
  233.             valueChanged = true;
  234.             this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
  235.             base.OnValueChanged(eventargs);
  236.         }
  237.     }
  238. }
  239.  
Code for the form containing the datagridview:
Expand|Select|Wrap|Line Numbers
  1. private void Form1_Load(object sender, EventArgs e)
  2. {
  3.     DateTimePickerColumn col = new DateTimePickerColumn();
  4.     dataGridView1.Columns.Add(col);
  5.     dataGridView1.RowCount = 5;
  6. }
  7.  
Reference from MSDN 2005- How to: Host Controls in Windows Forms DataGridView Cells
Jul 24 '09 #1
0 5655

Sign in to post your reply or Sign up for a free account.

Similar topics

3
14736
by: Peter | last post by:
I need to add a button to a DataGridView, but the button should only show up in the cell when user clicks on a cell in the DataGridView and disapear when user clicks off the cell. Does anyone know how to do that or has an example? Thank you Peter
0
1377
by: Bob | last post by:
1- Inability to easily reset datagridview combobox selection to null Solution - add a contextmenustrip to the column in which you have the combobox on the datagridview. show to user, something like Remove selection. In the onclick event Me.Datagridview1.CurrentRow.Cells.Item("YourColumnName").Value = System.DBNull.Value 2- You can use same technique for ordinary comboxes, instead of row in datagridview set value of the combobox bound...
3
3513
by: Alex Bibiano | last post by:
¿Are there free column types to use in my DataGridView? For exemple a datapicker, a maskedit, or a numeric type I know I can do it, but I'm searching for some implemented code.
1
2310
by: Rich | last post by:
Hello, I am reading data from a sql server table that is under replication. This table has the replicatin GUID column that is generated with replicatin. I am reading the data from a dataAdapter/Dataset using a dataview which is the data source for a datagridview control. When I scroll horizontally in the datagridview control and reach this GUID column (which is not at the end of the table) it raises the datagridview dataError event. ...
2
15163
by: Bob | last post by:
How do I show a calendar control or another appropriate control to pick a date and time for a cell in a column in a datagridview? Thanks for any help. Bob
1
3885
by: Bob | last post by:
Hi, I want to have a datetimepicker in a datecolumn. Found the source for creating a DTP column, but can't see how to convert an existing date column to be a DTP column. ie. My DataGridView is bound to a DataSet. Anybody done this? thanks Bob
2
10592
by: =?Utf-8?B?QXJuZSBCZXJ1bGRzZW4=?= | last post by:
I've downloaded some code relative to establishing a column on my DataGridView which allows me to use the DateTimePicker. So far so good. If I add a column using dim col as new CalendarColumn the grid works great. However...I need to assign an existing column ... from a database. How do I make datagridview1.columns("NoteDate") my CalendarColumn? Any suggestions?
0
3051
by: eddyman592 | last post by:
Ok, I'm trying to make a column in my data grid be a DateTimePicker column. I copied and pasted all the code from the msdn website. Now, the difference in my code and the microsoft code is that my datagrid is not in the startup form. Also, the form it's in is an MdiChild. So I get errors when the form containing the datagrid is opened. Next, when i go and take out the whole mdichild thing, the form with the datagrid won't recognize the...
0
2295
by: priyamtheone | last post by:
Can anyone provide me with a code example of how to use a datetimepicker cell in datagridview where in the datetimepicker column i can set the value of any cell to null or to any datetime according to my choice. And the format of the datetimepicker cell should be dd MMM yyyy. I checked a lot of examples in the forums including articles by Nils Jonsson, Pham Minh Tri and Claudio Grazioli but none of them works when the DGV is databound. It works...
0
8774
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9447
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9181
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6735
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.