John Ding
John Ding

Reputation: 31

How to display selected month from Calendar into text box in WPF?

I wanted to ask how can I display selected month from calendar and display into my text box? I tried to use ToString(), but it still didn't work. I'm thinking there's difference in date picker and calendar, still not sure. Can anyone please help me out here? Thanks alot. Here's my coding;

In xaml;

 Calendar Name ="dteSelectedMonth" DisplayMode="Year" SelectionMode="SingleDate" DisplayModeChanged="dteSelectedMonth_DisplayModeChanged" DisplayDateChanged="monthCalendar_DataChanged" 

In xaml.cs;

private void monthCalendar_DataChanged(object sender, CalendarDateChangedEventArgs e)
    {
        monthDisplay.Text = dteSelectedMonth.SelectedDate.ToString();
    }

enter image description here enter image description here

Upvotes: 1

Views: 1249

Answers (3)

mm8
mm8

Reputation: 169160

You could get the selected month using the DisplayDate property. Make sure that the IsLoaded property returns true before you try to set the Text property:

private void monthCalendar_DataChanged(object sender, CalendarDateChangedEventArgs e)
{
    if (IsLoaded && dteSelectedMonth.DisplayDate != null)
        monthDisplay.Text = dteSelectedMonth.DisplayDate.ToString("MMM");
}

Upvotes: 1

AJITH
AJITH

Reputation: 1175

Please check your monthDisplay textbox is null or not. This happens because the displayDteChanged event fires before the initialization of the textbox (If you have the declaration of TextBox before that of Calendar). Add a null check to handle this.

if (monthDisplay != null)
            monthDisplay.Text = e.AddedDate?.Month.ToString();

Upvotes: 0

Dmitry Vasilevich
Dmitry Vasilevich

Reputation: 21

Use CalendarDateChangedEventArgs object and its property AddedDate. When the event is fired, it will contain the previously selected day in the new month. Then you can convert it to any string format, e.g. to get the month.

Upvotes: 0

Related Questions