Question

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();
    }
}
Was it helpful?

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();
    }
}

OTHER TIPS

First, find out the first day of the week. You can do it similar to this. Then starting from this date assign the target text to each label.

You can do the latter in 7 lines of code, one for each label, or you can put your labels in an array, in your form initialization code and iterate through the array. Note, that putting the labels into the array will still require 7 lines. Finally you can use Form.Controls or Form.FindControl to find all your 7 labels in a loop based on their names.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top