I am trying to use the DateTime picker custom gridview column type from this MSDN example on How to host controls in DataGridViewCells. I want to display hour and minute in 24 hour format, without seconds or AM PM indicators.
I have set EditingControlFormattedValue to "HH:mm", and when not actually editing the value is displayed correctly.
When editing, if in the constructor of the CalendarEditingControl I set the editing control to CustomFormat = "HH:mm", the control displays the day of week and month. (!?)
When I instead use Format = DateTimePickerFormat.Time, the control shows AM or PM when editing.
How can I persuade this control to display only the parts of the DateTime value that I care about? (C#, VS 2008)
There are a few tweaks you need to to do the linked code to make it work the way you want:
Comment out the hard-coded line in CalendarCell() constructor (this.Style.Format = "d";)
Tell the CalendarEditingControl to use your custom-specified format:
In the designer, set the format you want (EditColumns->DefaultCellStyle->Format)
public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
{
this.Format = DateTimePickerFormat.Custom;
this.CustomFormat = dataGridViewCellStyle.Format;
// ... other stuff
}
I found I needed to make the following changes:
In the constructor of the CalendarCell change the format to 24 hour.
public CalendarCell()
: base()
{
// Use the 24hr format.
//this.Style.Format = "d";
this.Style.Format = "HH:mm";
}
In the constructor for the editing control specify to use a custom format. I've also taken the liberty of setting ShowUpDown true so you don't show the calendar icon when editing the cell:
public CalendarEditingControl()
{
//this.Format = DateTimePickerFormat.Short;
this.Format = DateTimePickerFormat.Custom;
this.CustomFormat = "HH:mm";
this.ShowUpDown = true;
}
Change EditingControlFormattedValue. This doesn't appear to actually be necessary but feels icky to leave as is.
// Implements the IDataGridViewEditingControl.EditingControlFormattedValue
// property.
public object EditingControlFormattedValue
{
get
{
//return this.Value.ToShortDateString();
return this.Value.ToString("HH:mm");
}
set
{
if (value is String)
{
try
{
// This will throw an exception of the string is
// null, empty, or not in the format of a date.
this.Value = DateTime.Parse((String)value);
}
catch
{
// In the case of an exception, just use the
// default value so we're not left with a null
// value.
this.Value = DateTime.Now;
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With