Create a control that inherits from DateTimePicker and handle the DTN_DATETIMECHANGE notification. Then handle the DataGridView EditingControlShowing event to add a handler for the new CheckedChanged event in DateTimePicker, or even you can create your own DataGridViewColumn and Cell type with DateTimePickerEx as EditingControl:
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; public class DateTimePickerEx : DateTimePicker { private bool _checked; private const int WM_REFLECT = 0x2000; public event CheckedChangedEventHandler CheckedChanged; public delegate void CheckedChangedEventHandler(object sender, System.EventArgs e); public DateTimePickerEx() { this._checked = this.Checked; } private void WmDateTimeChange(ref Message m) { NMDATETIMECHANGE nmdatetimechange = m.GetLParam(typeof(NMDATETIMECHANGE)); if (nmdatetimechange.dwFlags == GetDateTimeValues.GDT_NONE) { if (this.ShowCheckBox && !this.Checked) { this._checked = false; if (CheckedChanged != null) { CheckedChanged(this, EventArgs.Empty); } } } else { if (this.ShowCheckBox && this.Checked && !this._checked) { this._checked = true; if (CheckedChanged != null) { CheckedChanged(this, EventArgs.Empty); } } this.Value = SysTimeToDateTime(nmdatetimechange.st); } m.Result = IntPtr.Zero; } private bool WmReflectCommand(ref Message m) { if (m.HWnd == this.Handle) { long code = NMHDR.FromMessage(m).code; switch (code) { case FWEx.Win32API.DateTimePickerNotifications.DTN_DATETIMECHANGE: this.WmDateTimeChange(ref m); return true; } return false; } } [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")] protected override void WndProc(ref System.Windows.Forms.Message m) { if (m.Msg != 71 && m.Msg != 513) { switch ((WindowsMessages)m.Msg) { case WindowsMessages.WM_NOTIFY + WM_REFLECT: if (!this.WmReflectCommand(ref m)) { break; } return; break; } } base.WndProc(m); } private System.DateTime SysTimeToDateTime(SYSTEMTIME st) { return new System.DateTime(st.Year, st.Month, st.Day, st.Hour, st.Minute, st.Second); }
Handle DateTimePickerEx.CheckedChanged in DataGridView.EditingControlShowing:
private void dgv_EditingControlShowing(System.Object sender, System.Windows.Forms.DataGridViewEditingControlShowingEventArgs e) { switch (this.dgv.CurrentCellAddress.X) { case 0: // your DateTimePickerEx column number DateTimePickerEx dtp = e.Control as DateTimePickerEx; if (dtp != null) { dtp.CheckedChanged += (object sen, EventArgs ea) => { //TODO: Add your code here }; } break; } }
source share