Datetimepicker with custom dates

Asked

Viewed 154 times

2

I am developing a consultation marking system in Windows Forms and had the idea to include a DateTimePicker where only dates with available vacancies must be "clickable" by the user.

There’s a way to do it?

  • I never did but it seems there is a good discussion about it: http://stackoverflow.com/questions/27319417/disable-some-dates-in-datetimepicker-winform-c-sharp and http://stackoverflow.com/questions/2361691/how-do-i-disable-some-dates-on-a-datetimepicker-control. The possible solutions shown in these topics involve WPF+ Windows Forms and third-party Components. You may not have a native and easy solution to disable specific dates.

1 answer

2


I couldn’t find an option to restrict certain dates in the Datetimepicker component, you may need to use a third party component to do what you want as suggested by the @rodrigorf comment or create your own.

However, there is an alternative that is to manipulate the event Valuechanged of the component and check the dates that are being selected. You can check through a list of dates like this:

public List<DateTime> datasComConsultas = new List<DateTime>();

then just check the dates that are being selected in the event ValueChanged:

private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
    if (datasComConsultas.Any(d => d == DateTime.Parse(dateTimePicker1.Text))) MessageBox.Show("Esta data nao esta disponivel");
    else MessageBox.Show("Data disponivel");
}

This way you can check the dates that do not have vacancies available or the other way around, but this is not the perfect way, however it can help you.

Follow the full example code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace DatePickerExCustom
{
    public partial class Form1 : Form
    {
        public List<DateTime> datasComConsultas = new List<DateTime>();

        public Form1()
        {
            InitializeComponent();
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            if (datasComConsultas.Any(d => d == DateTime.Parse(dateTimePicker1.Text))) MessageBox.Show("Esta data nao esta disponivel");
            else MessageBox.Show("Data disponivel");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            datasComConsultas = new List<DateTime>
            {
                new DateTime(2017, 02, 04),
                new DateTime(2017, 02, 05),
                new DateTime(2017, 02, 10)
            };            
        }
    }
}

Source of the solution based on this post.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.