如何在Windows应用程序中显示datetimepicker中的未来日期?

时间:2012-08-09 05:11:28

标签: c# .net-3.5

我正在创建一个Windows应用程序,我使用了两个表单。第一个表单包含第一个datetimepicker,第二个表单包含第二个datetimepicker。如果我在第一个datetimepicker中选择任何日期,则在第二个datetimepicker中显示未来日期,即6个月差异。下面是示例

如果我在第一个datetimepicker中选择日期,即8/9/2012(mm:dd:yyy),那么

在第二个datetimepicker显示日期,即2/8/2013(mm:dd:yyy),第二个datetimepicker必须有6个月的差异。

2 个答案:

答案 0 :(得分:0)

关于你的问题的第二次阅读,我现在看到你有两种不同的形式。您需要以第一种形式公开DateTimePicker.ValueChanged事件,然后以第二种形式公开DateTimePicker.Value属性。例如:

class DateEventArgs : EventArgs
{
    public DateTime Date {get; private set;}

    public DateEventArgs(DateTime d) 
        : base()
    {
        this.Date = d;
    }
}

class FirstForm : Form
{
    DateTimePicker dtp = new DateTimePicker();

    public event EventHandler<DateEventArgs> DateSelected;
    protected virtual void OnDateSelected(DateEventArgs e)
    {
        EventHandler<DateEventArgs> handler = DateSelected;
        if(handler != null) handler(this, e);
    }

    public FirstForm()
    {
        this.Controls.Add(dtp);
        dtp.ValueChanged += new EventHandler(dtp_ValueChanged);
    }

    void dtp_ValueChanged(object sender, EventArgs e)
    {
        DateEventArgs dea = new DateEventArgs(dtp.Value.Date);
        OnDateSelected(dea);
    }
}

class SecondForm : Form
{
    DateTimePicker dtp = new DateTimePicker();

    public DateTime SelectedDate
    {
        set { dtp.Value = value; }
    }

    public SecondForm()
    {
        this.Controls.Add(dtp);
    }
}

static class Controller
{
    FirstForm f1;
    SecondForm f2;

    static void Go()
    {
        f1 = new FirstForm();
        f2 = new SecondForm();
        f1.DateSelected += new EventHandler<DateEventArgs>(f1_DateSelected);

        f1.Show();
        f2.Show();
    }

    static void f1_DateSelected(object sender, DateEventArgs e)
    {
        f2.SelectedDate = e.Date.AddMonths(6);
    }
}

答案 1 :(得分:0)

这应该有帮助

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // Initialize picker 
        dateTimePicker2.Value = Convert.ToDateTime(ObjectForValue1).AddMonths(6);
    }

    private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
    {
        // Set title bar to selected date.
        DateTime result = dateTimePicker2.Value;
        this.Text = result.ToString();
    }
    }
}