Overview

Namespace: TheTechIdea.Beep.Winform.Controls

Assembly: TheTechIdea.Beep.Winform.Controls.dll

Inheritance: BeepDatePicker → BaseControl → Control

Implements: IBeepComponent (via BaseControl), IBeepUIComponent (via BaseControl)

Toolbox: Beep Controls category, display name "Beep Date Picker"

BeepDatePicker is a feature-rich date/time input control that provides a clean, headerless design where the entire control surface is rendered directly via owner-draw GDI+. There are no child TextBox or Button controls; instead, text, calendar icon, and dropdown button are all painted directly. It supports 15 predefined date format styles, custom format strings, culture-aware parsing/formatting, a calendar popup via BeepDatePickerView, business application features (min/max dates, weekends, excluded dates, auto-adjust to business days), validation with visual error feedback, keyboard navigation (F4/Alt+Down for popup), and auto-submit behavior.

The control is defined in a single source file: BeepDatePicker.cs (1082 lines). Related companion controls (BeepDatePickerView, BeepTimePicker, BeepDateDropDown, BeepDateTimePicker) live in the same Dates\ directory and provide extended calendar/time selection capabilities.

Key Features

  • Owner-draw rendering: No child controls; all text, borders, and icon painted directly for maximum performance and theme integration
  • 15 date format styles: ShortDate, LongDate, YearMonth, Custom, FullDateTime, ShortDateTime, DayMonthYear, ISODate, ISODateTime, TimeOnly, ShortTime, MonthDay, DayOfWeek, RFC1123, UniversalSortable
  • Culture-aware: Respects the assigned CultureInfo for both formatting and parsing
  • Inline keyboard editing: Type dates directly with character-level validation; press Enter to commit, Escape to cancel editing
  • Calendar popup: Opens BeepDatePickerView inside a BeepPopupForm positioned below the control
  • Popup time spinner: The calendar view includes an inline time spinner (up/down chevrons) for adjusting hours/minutes
  • Date constraining: MinDate, MaxDate, ExcludedDates, Weekends
  • Business context methods: Pre-built configurations for Due Date, Creation Date, Event Scheduling, Birth Date, Appointment
  • Auto-adjust to business days: Skips weekends automatically when enabled
  • Validation: Visual error highlighting (error backcolor, tooltip), DateValidationFailed event
  • AutoSubmit: Fires DateSubmitted immediately when a date is selected from the popup
  • Theme integration: Uses CalendarBackColor, CalendarForeColor, CalendarBorderColor, CalendarTitleForColor, DateFont / BodyMedium tokens
  • Keyboard shortcuts: F4 or Alt+Down toggles popup; Escape cancels editing; F4 handled in KeyDown
  • Placeholder text: Auto-generated from the format string (e.g., "DD/MM/YYYY" replaces format codes with placeholder letters)
  • AutoHeight / AutoSize: Optional auto-sizing modes for height and width
  • Material Design integration: Convenience property aliases (DatePickerLabel, DatePickerHelperText, DatePickerErrorText)
  • Value binding: Implements SetValue/GetValue for data-binding; BoundProperty defaults to "SelectedDateTime"
  • Highlighted dates list: Custom dates can be visually highlighted in the calendar

Properties

PropertyTypeDefaultDescription
SelectedDateTimeDateTimeDateTime.NowGets or sets selected date/time. Fires SelectedDateTimeChanged and DateChanged events on change.
ValueDateTime(alias)Alias for SelectedDateTime for compatibility with existing code. [Browsable(false)]
SelectedDatestring""Gets or sets selected date as formatted string. Parses via culture; applies validation.
DateFormatStyleDateFormatStyleShortDateTimePredefined date format style from the 15-value DateFormatStyle enum.
DateFormatstring"d"Custom format string, used when DateFormatStyle = Custom. Falls back to culture short date if empty.
CultureCultureInfoCurrentCultureCulture for date formatting and parsing. Defaults to current culture.
MinDateDateTime?nullMinimum allowed date for selection.
MaxDateDateTime?nullMaximum allowed date for selection.
AllowEmptybooltrueWhether empty/null dates are allowed.
ShowDropDownbooltrueWhether to show the calendar dropdown button icon.
ReadOnlyboolfalseMakes the date picker read-only (display only).
DateContextstring"Date Selection"Context description for this picker (e.g., "Due Date", "Start Date").
AutoAdjustToBusinessDaysboolfalseAutomatically adjust selected dates to skip weekends (business days only).
HighlightTodaybooltrueHighlight today's date in the calendar popup.
Weekendsstring[]["Saturday","Sunday"]Days of the week considered as weekends (culture-independent).
ExcludedDatesList<DateTime>empty listSpecific dates to exclude from selection.
HighlightedDatesList<DateTime>empty listDates to highlight in the calendar popup.
ShowValidationIconbooltrueShow validation error visual (tooltip + error backcolor) when date is invalid.
AutoSubmitboolfalseAutomatically submit date when selected from calendar popup (fires DateSubmitted).
ValidationErrorMessagestring""Current validation error message (read-only, private setter).
AutoHeightbooltrueAutomatically calculates height based on font and padding.
AutoSizeboolfalseAuto-sizes width to fit formatted date text. Height governed by AutoHeight.
DatePickerLabelstring(base LabelText)Material Design convenience binding to LabelText.
DatePickerHelperTextstring(base HelperText)Material Design convenience binding to HelperText.
DatePickerErrorTextstring(base ErrorText)Material Design convenience binding to ErrorText.
DatePickerHasErrorbool(base HasError)Material Design convenience binding to HasError.
DatePickerAutoSizeForMaterialbooltrueWhether material sizing compensation is applied.

Methods

MethodSignatureDescription
ConfigureForDueDatevoid ConfigureForDueDate()Sets ShortDateTime, context "Due Date", MinDate=today, business days, validation on.
ConfigureForCreationDatevoid ConfigureForCreationDate()Sets ShortDate, context "Creation Date", MaxDate=today, read-only, no dropdown.
ConfigureForEventSchedulingvoid ConfigureForEventScheduling()Sets FullDateTime, context "Event Date", MinDate=today, AutoSubmit.
ConfigureForBirthDatevoid ConfigureForBirthDate()Sets ShortDate, context "Birth Date", MaxDate=today, MinDate=120 years ago.
ConfigureForAppointmentvoid ConfigureForAppointment()Sets ShortDateTime, context "Appointment Date", MinDate=today, MaxDate=6 months out, AutoSubmit.
AddBusinessHolidaysvoid AddBusinessHolidays(int year)Adds New Year's Day, Christmas Day, Boxing Day to ExcludedDates for given year.
SetBusinessDateRangevoid SetBusinessDateRange(DateTime start, DateTime end)Sets MinDate/MaxDate; clamps current selection into range.
GetNextBusinessDayDateTime GetNextBusinessDay(DateTime date)Returns the next date that is not a weekend and not in ExcludedDates.
IsDateValidbool IsDateValid(DateTime date)Checks against MinDate, MaxDate, ExcludedDates, Weekends (if auto-adjust enabled).
GetCurrentFormatstring GetCurrentFormat()Returns the resolved .NET format string based on DateFormatStyle, Culture, and DateFormat.
SetValueoverride void SetValue(object value)Accepts DateTime, string, or object. Parses if needed. Sets SelectedDateTime.
GetValueoverride object GetValue()Returns SelectedDateTime if not MinValue, otherwise null.
Resetvoid Reset()Resets SelectedDateTime to DateTime.Now.
Clearvoid Clear()Clears to DateTime.MinValue if AllowEmpty; clears validation error.
ApplyThemeoverride void ApplyTheme()Applies CalendarBackColor/ForeColor/BorderColor, DateFont token, icon pre-rendering in background.
Drawoverride void Draw(Graphics g, Rectangle rect)Container draw override for use by BeepGridPro and hosting controls.
DrawContentprotected override void DrawContent(Graphics g)Called by BaseControl. Delegates to PaintCore for actual rendering.
GetPreferredSizeoverride Size GetPreferredSize(Size proposedSize)Delegates to base. Used by layout engine.

Events

EventArgsDescription
SelectedDateTimeChangedEventArgsFired whenever SelectedDateTime changes (direct assignment or popup selection).
DateChangedDateChangedEventArgsFired with old and new DateTime values on change (OldDate, NewDate).
DateSubmittedDateSubmittedEventArgsFired when date is auto-submitted (AutoSubmit=true) or committed via popup OK.
DateValidationFailedDateValidationEventArgsFired when a date fails business rule validation (range, weekends, excluded).
CalendarOpenedEventArgsFired when the calendar popup opens.
CalendarClosedEventArgsFired when the calendar popup closes.
CalendarOkClickedDateTimeDialogResultEventArgsBubbles up the OK button click from the calendar view with the selected DateTime.
CalendarCancelClickedDateTimeDialogResultEventArgsBubbles up the Cancel button click from the calendar view.

Event Args Classes (defined in BeepDatePicker.cs)

ClassPropertiesDescription
DateChangedEventArgsDateTime OldDate, DateTime NewDateCarries the old and new date values for change tracking.
DateSubmittedEventArgsDateTime SelectedDate, string ContextCarries the submitted date and its context string.
DateValidationEventArgsDateTime InvalidDate, string ErrorMessageCarries the rejected date and the reason for rejection.
DateTimeDialogResultEventArgsDateTime? SelectedDateTime, string Context, bool IsConfirmedCarries the dialog result with confirmation flag, selected date/time, and context.

Theming

BeepDatePicker integrates with the BeepThemesManager through the ApplyTheme() override. It reads from the following IBeepTheme tokens:

Theme TokenPurposeFallback
CalendarBackColorControl background color (BackColor)None (uses base)
CalendarForeColorText color for the date displayForeColor (base)
CalendarBorderColorBorder and divider colorBorderColor
CalendarTitleForColorIcon tint color for the calendar SVG iconForeColor
DateFontPrimary text font (via BeepThemesManager.ToFont)BodyMedium token
BodyMediumFallback font token when DateFont is not setSystemFonts.DefaultFont
TextBoxErrorBackColorBackground when validation failsColor.Empty

The calendar icon SVG is pre-rendered in multiple sizes (8, 12, 14, 16, 18, 20, 24, 28, 32 px) via Task.Run for smooth scaling. The ApplyTheme method also propagates themes to child objects (calendarIcon, _calendarView) and calls InvalidateOnce() for batched repaint. The _textFont is resolved with a safe fallback chain: DateFont token → BodyMedium token → SystemFonts.DefaultFont.

Examples

Example 1: Basic Usage with Due Date Configuration

var datePicker = new BeepDatePicker
{
    Location = new Point(20, 20),
    Width = 250,
    Theme = myTheme // Optional IBeepTheme instance
};
datePicker.ConfigureForDueDate();
this.Controls.Add(datePicker);

datePicker.DateSubmitted += (s, e) =>
{
    Console.WriteLine($"Due date submitted: {e.SelectedDate} ({e.Context})");
};

Example 2: Custom Format with Validation

var datePicker = new BeepDatePicker
{
    DateFormatStyle = DateFormatStyle.ISODateTime,  // "yyyy-MM-dd HH:mm:ss"
    MinDate = DateTime.Today.AddYears(-1),
    MaxDate = DateTime.Today.AddYears(1),
    AutoAdjustToBusinessDays = true,
    Weekends = new[] { "Friday", "Saturday" }, // Custom weekend
    ShowValidationIcon = true
};

datePicker.DateValidationFailed += (s, e) =>
{
    MessageBox.Show(e.ErrorMessage, "Invalid Date",
        MessageBoxButtons.OK, MessageBoxIcon.Warning);
};

Example 3: Data-Binding and Value Integration

datePicker.SetValue(DateTime.Today.AddDays(7));
datePicker.SelectedDate = "2025-12-31";

var value = datePicker.GetValue(); // DateTime? (null if empty/cleared)

datePicker.Reset(); // Set to DateTime.Now
datePicker.Clear(); // Set to DateTime.MinValue (if AllowEmpty)

datePicker.AddBusinessHolidays(DateTime.Now.Year);
var nextBiz = datePicker.GetNextBusinessDay(DateTime.Today);

Example 4: Read-Only Display Mode

var displayPicker = new BeepDatePicker
{
    SelectedDateTime = new DateTime(2025, 6, 15, 14, 30, 0),
    DateFormatStyle = DateFormatStyle.ShortDateTime,
    ReadOnly = true,
    ShowDropDown = false,
    AllowEmpty = false
};
// User cannot edit or open the calendar popup

Example 5: Material Design Integration

var materialPicker = new BeepDatePicker
{
    PainterKind = BaseControlPainterKind.Material,
    DatePickerLabel = "Appointment Date",
    DatePickerHelperText = "Select a future date and time",
    DatePickerAutoSizeForMaterial = true
};

materialPicker.DatePickerHasError = true;
materialPicker.DatePickerErrorText = "Date is in the past";

Example 6: Business Date Range and Appointment Configuration

datePicker.ConfigureForAppointment();
datePicker.SetBusinessDateRange(
    DateTime.Today.AddDays(1),
    DateTime.Today.AddMonths(3));
datePicker.AddBusinessHolidays(DateTime.Now.Year);

Architecture

BeepDatePicker uses a headerless, owner-draw design with no child controls. The layout is computed in PaintCore using three layout constants: ButtonWidth=24, Padding=3. The right side of the control contains the dropdown area with a dividing line and a calendar SVG icon.

When the user clicks the dropdown area or presses F4/Alt+Down, a BeepPopupForm is created hosting a BeepDatePickerView which provides a full calendar grid with navigation, time spinner, and OK/Cancel footer links. The popup closes on OK (validates date, fires events) or Cancel (fires CancelClicked only).

File breakdown (Dates directory):

FileResponsibility
BeepDatePicker.cs (1082 lines)Main date picker: rendering (PaintCore), keyboard input, business logic, popup management, event args classes
BeepDatePickerView.cs (926 lines)Calendar popup view: month grid, day selection, time spinner, OK/Cancel footer, header with nav chevrons
BeepTimePicker.cs (1278 lines)Standalone time picker with TextBox, spin buttons, dropdown, 6 time formats, business features
BeepDateTimePicker.cs (37 lines)Full-featured date/time picker stub (multi-mode: Single, Range, Multiple, Appointment, etc.)
BeepDateTimePicker.Core.csCore fields, events, initialization, constructor for BeepDateTimePicker
BeepDateTimePicker.Properties.csAll properties for BeepDateTimePicker
BeepDateTimePicker.Events.csEvent handlers (mouse, keyboard, context menu)
BeepDateTimePicker.Methods.csPublic methods (node operations, search)
BeepDateTimePicker.Drawing.csDrawContent override and painting delegation
BeepDateDropDown.cs (47 lines)Inline-editing date dropdown inheriting from BeepTextBox
BeepDateDropDown.Core.csCore fields, events, initialization
BeepDateDropDown.Properties.csAll properties (Mode, SelectedDateTime, constraints)
BeepDateDropDown.Events.csEvent handlers
BeepDateDropDown.Methods.csDate parsing, formatting, validation
BeepDateDropDown.Drawing.csDrawContent override
BeepDateDropDown.SegmentEditing.csSegment-level editing for masked input
BeepDateDropDown.Sync.csSynchronization between text and calendar
Models/enums.csAll date/time enumerations (17 enums: DatePickerMode, ReturnDateTimeType, etc.)
Models/DateTimePickerModels.csDateTimePickerEventArgs class
Models/DateTimePickerProperties.csDateTimePicker property model class
Models/DatePickerModeMapping.csMaps DatePickerMode to view mode enumerations
Internal/DaysGrid.csInternal days grid layout helper
ShadowPainterFactory.csFactory for shadow painting
Painters/ (20 files)Per-mode painting strategies (Single, Range, Appointment, Compact, MonthView, YearView, etc.)
HitHandlers/ (20 files)Per-mode hit test handlers for mouse/keyboard interaction
Helpers/ (5 files)ComboBox helper, QuickButton helper, HitTest helper, Layout helper, Input helper

Companion Controls

BeepDatePickerView

A modern calendar view control (BaseControl) that displays a month calendar with navigation chevrons, responsive cell sizing, time spinner (up/down chevrons), and OK/Cancel action buttons. Used internally by BeepDatePicker as the popup calendar. Features responsive layout with minimum size enforcement (320x420 default, MinSize calculated from layout constants), theme-aware color tokens (CalendarSelectedDateBackColor, CalendarSelectedDateForColor, CalendarTodayForeColor, CalendarDaysHeaderForColor, CalendarTitleForColor), and font tokens (CalendarTitleFont, DaysHeaderFont, DateFont, CalendarSelectedFont, FooterFont). Properties: SelectedDateTime (DateTime?), ShowTime (bool, default true), Context (string). Events: DateTimeSelected, Cancelled, OkClicked, CancelClicked (both with DateTimeDialogResultEventArgs).

BeepTimePicker

A standalone time picker with a borderless TextBox child for inline editing, a dropdown button (clock SVG icon) that opens a BeepPopupForm with hour/minute/AM-PM ListBoxes, and optional spin up/down BeepButton children. Supports 6 time format styles (TwelveHour, TwentyFourHour, TwelveHourWithSeconds, TwentyFourHourWithSeconds, HoursOnly, Custom), minute interval/snapping (1-60), business hours validation (BusinessStartTime 9:00, BusinessEndTime 17:00), 24-hour toggle, seconds editing toggle, and context configurations with pre-built methods: ConfigureForMeetingTime(), ConfigureForAppointment(), ConfigureForShiftTime(), ConfigureForDeadline(). Events: SelectedTimeChanged, TimeChanged (TimeChangedEventArgs), TimeSubmitted (TimeSubmittedEventArgs), TimeValidationFailed (TimeValidationEventArgs), TimePickerOpened, TimePickerClosed.

BeepDateDropDown

An inline-editing date dropdown inheriting from BeepTextBox for full text editing capabilities (input masking, AutoComplete, Undo/Redo, selection/caret management). Supports single dates, date ranges ("MM/dd/yyyy - MM/dd/yyyy"), and date-time ranges with proper formatting. The dropdown calendar is a BeepDateTimePicker shown in a popup. 7 partial files: Core, Properties, Events, Methods, Drawing, SegmentEditing, Sync. Features: inline masking, F4 dropdown shortcut, culture-specific formatting, min/max date constraints, theme integration, validation feedback.

BeepDateTimePicker

A full-featured date/time picker control supporting 18 functional modes (Single, SingleWithTime, Range, RangeWithTime, Multiple, Appointment, Timeline, Quarterly, Compact, ModernCard, DualCalendar, WeekView, MonthView, YearView, SidebarEvent, FlexibleRange, FilteredRange, Header). Uses a pluggable painter/hit-handler architecture with 20 painter strategies per mode and 20 hit handler strategies per mode. Incomplete implementation (stub state with 8 partial files).

Enumerations

DateFormatStyle (from Beep.Vis.Modules2.0)

ValueFormat StringExample Output
ShortDateCulture ShortDatePattern"6/15/2025"
LongDateCulture LongDatePattern"Sunday, June 15, 2025"
YearMonth"MMMM yyyy""June 2025"
CustomDateFormat propertyUser-defined
FullDateTimeLongDatePattern + LongTimePattern"Sunday, June 15, 2025 2:30:00 PM"
ShortDateTimeShortDatePattern + " HH:mm""6/15/2025 14:30"
DayMonthYear"dd MMMM yyyy""15 June 2025"
ISODate"yyyy-MM-dd""2025-06-15"
ISODateTime"yyyy-MM-dd HH:mm:ss""2025-06-15 14:30:00"
TimeOnly"HH:mm:ss""14:30:00"
ShortTime"HH:mm""14:30"
MonthDay"MMMM dd""June 15"
DayOfWeek"dddd""Sunday"
RFC1123"ddd, dd MMM yyyy HH:mm:ss 'GMT'""Sun, 15 Jun 2025 14:30:00 GMT"
UniversalSortable"yyyy-MM-dd HH:mm:ss'Z'""2025-06-15 14:30:00Z"

TimeFormatStyle (from BeepTimePicker.cs)

ValueFormatExample
TwelveHour"h:mm tt""2:30 PM"
TwentyFourHour"HH:mm""14:30"
TwelveHourWithSeconds"h:mm:ss tt""2:30:45 PM"
TwentyFourHourWithSeconds"HH:mm:ss""14:30:45"
HoursOnly"HH" or "h tt""14" or "2 PM"
CustomTimeFormat propertyUser-defined

DatePickerMode (from Models/enums.cs)

Defines functional mode for BeepDateTimePicker/BeepDateDropDown. 18 values: Single, SingleWithTime, Range, RangeWithTime, Multiple, Appointment, Timeline, Quarterly, Compact, ModernCard, DualCalendar, WeekView, MonthView, YearView, SidebarEvent, FlexibleRange, FilteredRange, Header.

ReturnDateTimeType (from Models/enums.cs)

Defines return value type: Date, DateTime, DateRange, DateTimeRange, MultipleDates, TimeOnly.

Additional Date Enums (from Models/enums.cs)

DateDropDownStyle: Default, Modern, Classic, Custom — DatePickerFormat: Long, Short, Time, Custom, ShortDate — DatePickerView: Days, Months, Years — DatePickerSelectionMode: Single, Multiple, Range — DatePickerCalendarType: Gregorian, Julian, Hebrew, Hijri, ThaiBuddhist, UmAlQura — DatePickerFirstDayOfWeek: Sunday through Saturday — DatePickerWeekNumbers: None, FirstDay, FirstFullWeek, FirstFourDayWeek, Left — DatePickerMonthDisplay: Full, Abbreviated, Numeric — DatePickerYearDisplay: Full, Abbreviated, TwoDigit — DatePickerHighlightCurrentDate: None, Background, Border, Both — DatePickerHighlightSelectedDate: None, Background, Border, Both — DatePickerDisabledDateStyle: GrayedOut, Hidden, Custom — DatePickerAnimationType: None, Fade, Slide, Zoom — DateTimePickerHitArea: 40+ hit areas covering all interactive zones (Header, DayCell, QuickButton, TimeSpinner, etc.).