Search code examples
c#winformsvisual-studio-2010monthcalendar

Month Calendar display dates for Monday - Sunday


I am creating a small program which will soon develop into a timetable and I am practicing using the C# MonthCalendar. So far I have managed to display the date selected onto a text label, however I am looking do achieve something slightly different, which I am struggling with.

I have placed seven labels on a form. When I click on a date, I want all seven labels to be populated with dates that correspond to the specific week on which the selected date is located. Can anyone suggest what I need to do to achieve this.

The problem that i want to resolve: Lets say I select a date from the calendar. E.g 22/01/1013 so on the labels I want to display all the dates in that week starting from the 21st - 27th Jan 2012

To clarify this further:

This is the interface I have come up with: enter image description here

And the code that I have so far:

 public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Enabled = true;
        }
        private void button1_Click(object sender, EventArgs e)
        {
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        DateTime dt = DateTime.Now;
        label8.Text = dt.ToString();
    }

    private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
    {
        label1.Text = monthCalendar1.SelectionStart.ToString();
    }
}

Solution

  • From the answer of zespri and I got this idea from this answer.

    class Program
    {
        static void Main(string[] args)
        {
            DateTime t = DateTime.Now; //Your selected date from Calendar
            t -= new TimeSpan((int)t.DayOfWeek, 0, 0, 0);
            Console.WriteLine("\tstart: " + t.Date.ToShortDateString());
            Console.WriteLine("\tend: " + t.Date.AddDays(7).ToShortDateString());
            Console.WriteLine("\t" + new string('-', 25));
    
            for (int i = 0; i < 7; i++)
            {
                var d = t.AddDays(i);
                if (d.DayOfWeek >= DayOfWeek.Monday && d.DayOfWeek <= DayOfWeek.Friday) //Range: Monday to Friday
                    Console.WriteLine(d.DayOfWeek + " : " + d);
            }
            Console.ReadLine();
        }
    }