Search code examples
winformsdatagridviewcustomcolumn

format datetimepicker in datagridview column


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)


Solution

  • 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
      }