Datetimepicker format in datagridview column

I am trying to use the custom column type of a DateTime picker table from this MSDN example in How to Place Controls in DataGridViewCells. I want to display hour and minute in 24 hour format, without seconds or AM PM indicators.

I set EditingControlFormattedValue to "HH: mm" and when the actual editing of the value does not display correctly.

When editing, if I set the edit control to CustomFormat = "HH: mm" in the CalendarEditingControl constructor, the control displays the day of the week and month. (!?)

When I use Format = DateTimePickerFormat.Time instead, the control shows AM or PM when editing.

How can I convince this control to display only the DateTime values ​​that concern me? (C #, VS 2008)

+3
source share
2 answers

There are several settings that you need to execute the related code in order for it to work the way you want:

  • Comment out the gated string in the CalendarCell () ( this.Style.Format = "d";) constructor

  • Tell CalendarEditingControl to use its format:

  • In the constructor, set the desired format (EditColumns-> DefaultCellStyle-> Format)

    public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
    {
        this.Format = DateTimePickerFormat.Custom;
        this.CustomFormat = dataGridViewCellStyle.Format;
        // ... other stuff
    }
    
+3
source

I found that I need to make the following changes:

In the CalendarCell constructor, change the format to 24 hours.

public CalendarCell()
    : base()
{
    // Use the 24hr format.
     //this.Style.Format = "d";
     this.Style.Format = "HH:mm";
}

. ShowUpDown true, :

public CalendarEditingControl()
{
    //this.Format = DateTimePickerFormat.Short;
    this.Format = DateTimePickerFormat.Custom;
    this.CustomFormat = "HH:mm";
    this.ShowUpDown = true;
}

EditingControlFormattedValue. , -, , , , .

// 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;
            }
        }
    }
}
+1

All Articles