问题描述:

I was wondering if you could use one month calendar to populate 2 text boxes on a windows form. One for the beginning date and one for the end date. I can figure out how to populate both text boxes with the click on the calendar but now how to populate start date with click 1, clear the calendar, then populate end date with the 2nd calendar click.

Is this possible, and if so how would I achieve this in C# windows form?

网友答案:

You can handle the "Date Selected" event as seen below:

    public Form1()
    {
        InitializeComponent();
        mthCalendarMaster.DateSelected += mthCalendarMaster_DateSelected;
    }

    private void mthCalendarMaster_DateSelected(object sender, DateRangeEventArgs e)
    {
        if (string.IsNullOrWhiteSpace(textBox1.Text))
            textBox1.Text = e.Start.ToShortDateString();
        else
            textBox2.Text = e.Start.ToShortDateString();
    }

Note: It is not the greatest idea to define your event handlers in the form's constructor.

网友答案:

This will make the 2 textboxes have the currently startdate of the month and end date all binded through the binding source :

        BindingSource source = new BindingSource();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SetSource();
            textBox1.DataBindings.Add("Text", source, "Start", true);
            textBox2.DataBindings.Add("Text", source, "End", true);
        }

        private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
        {
            SetSource();
        }

        private void SetSource()
        {
            source.DataSource = monthCalendar1.GetDisplayRange(true);
        }
    }

We call SetSource() in the DateChanged handler to keep the textboxes sync with calendar iteration(previous month,next month...).

相关阅读:
Top