简体   繁体   中英

Get selected month from Winforms month calendar?

I have a MonthCalendar control on my form. I have set it so that it selects an entire week at a time (from Sun to Sat).

At the top of the control, the user is able to select a month. How can I obtain the month that the user has selected? Issues rise when there is a week that contains days from two different months.

Eg If user selects the week of Nov 29 2015 to Dec 5 2015 and has the month of November selected in the control. They could have December selected as well, I don't know how to tell.

Code for selecting week (it doesn't select from Sunday to Saturday but that's a problem for later):

int i = (int)MonthView1.SelectionStart.DayOfWeek;
Date d = MonthView1.SelectionStart;
MonthView1.SelectionStart = d.AddDays(1 - i);
MonthView1.SelectionEnd = d.AddDays(7 - i);

Thanks!

This will use the month of the start of the selection. Is this what you want?

    private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
    {
        DateTime d = monthCalendar1.SelectionRange.Start;
        Console.WriteLine(d.Month.ToString());
    }

You can easily change it to monthCalendar1.SelectionRange.End if using start is not what you want.

EDIT:

Putting your selection code in MouseDown event, I noticed the small selection (dotted line) box will always be on Monday, which is also start of selection. That means if Monday lies on the previous month, monthCalender will scroll to the previous month. Hence using monthCalendar1.SelectionRange.Start should fulfill your requirements.

EDIT2:

Maybe you tried to put everything in 1 callback? Here's my complete code. It won't glitch.

(Though the monthCalendar1_DateChanged might be called multiple times when you do a mouse down. The LAST time it is called will give you the correct Month)

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.monthCalendar1.DateChanged += new System.Windows.Forms.DateRangeEventHandler(this.monthCalendar1_DateChanged);
        this.monthCalendar1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.monthCalendar1_MouseDown);
    }

    private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
    {
        DateTime d = monthCalendar1.SelectionRange.Start;
        Console.WriteLine(d.Month.ToString()); //Get the month selected. 
    }

    private void monthCalendar1_MouseDown(object sender, MouseEventArgs e)
    {
        int i = (int)monthCalendar1.SelectionStart.DayOfWeek;
        DateTime d = monthCalendar1.SelectionStart;
        monthCalendar1.SelectionStart = d.AddDays(1 - i);
        monthCalendar1.SelectionEnd = d.AddDays(7 - i);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM