Hello,

In the form1 load event I am running this code

        Dim NewCalendar As New MonthCalendar
        NewCalendar.Name = "DateSelecter"
        NewCalendar.Size = New Size(80, 80)
        NewCalendar.Location = New Point(100, 100)
        NewCalendar.Visible = True

        AddHandler NewCalendar.DateSelected, AddressOf DateSelecter_DateSelected

        Me.Controls.Add(NewCalendar)

However I can not work out how to get the value from the month calendar, so my question is how can I get the value of the month calendar in the DateSelecter_DateSelected sub.

Kindest regards,

Minko

Dani AI

Generated

The approach suggested by is correct: the DateSelected handler receives a DateRangeEventArgs that describes the selected date(s). For many simple cases it’s easiest to read the calendar’s selection directly from the control (rather than only from the event args), and to control whether a single date or a range is allowed.

' inside the DateSelected handler
Dim cal = TryCast(sender, MonthCalendar)
If cal IsNot Nothing Then
    Dim chosenDate As Date = cal.SelectionStart.Date
    ' use chosenDate for display, comparison, or storage
End If

Setting MaxSelectionCount = 1 forces a single-date selection so SelectionStart and SelectionEnd are equal. If multi-day ranges are allowed, DateRangeEventArgs.Start/End (or SelectionRange.Start/End) reflect the range and can be used to compute a TimeSpan. Remember that the DateTime value includes a time component (usually midnight); use .Date or a stable string format (for example ISO yyyy-MM-dd) when comparing or storing dates.

Common pitfalls: the event won’t fire if the handler wasn’t attached correctly or if the control was created on a non-UI thread. For runtime-created controls, attach the handler and add the control to the form before relying on user interaction. If only a single date is needed, consider using a DateTimePicker instead of a MonthCalendar for a simpler UX.

Recommended Answers

All 2 Replies

You can try something like this:

Dim WithEvents MonthCalendar1 As New MonthCalendar

Private Sub MC1_DateChanged(sender As Object, e As DateRangeEventArgs) Handles MonthCalendar1.DateSelected
    'This will get the dates
    Dim dtStart As Date = e.Start
    Dim dtEnd As Date = e.End

    'This will create a timespan from those dates.
    Dim dtRange As TimeSpan = dtEnd - dtStart
End Sub

Thank you very much for the help, it solved my problem so I will mark this as solved.

Many thanks,

Minko

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.