Passing a Date Value from one Windows From to Another Form in C#

前端 未结 4 1109
轮回少年
轮回少年 2021-01-16 16:33

I am working on a very complex project and I am very very new to the windows Project.
I have 2 Forms :

  • ViewSchedule.cs
  • Sch
4条回答
  •  轮回少年
    2021-01-16 17:14

    The simplest way is to make sure that these two variables that define the two dates are public static so that they can be accessed through the other form. If you'd like to update the other form only if the value is changed. Then, I'd suggest you to have a Timer in the second form and a bool in the first form that indicates whether the date is changed or not.

    Example

    ViewSchedule.cs

    //These values must be static and public so that they'd be accessible through the second form
    public static bool DateChanged = false;
    public static DateTime _fromDate;
    public static DateTime _toDate;
    
    private void SetValues()
    {
        _fromDate = dtFromDate.DateTime.ToUniversalTime();
        _toDate = dtToDate.DateTime.ToUniversalTime();
        DateChanged = true; //Set DateChanged to true to indicate that there has been a change made recently
    }
    

    Scheduler.cs

    public Scheduler()
    {
        InitializeComponent();
        timer1.Tick += new EventHandler(timer1_Tick); //Link the Tick event of timer1 to timer1_Tick
    }
    
    DateTime _fromDate; //Set a new variable of name _fromDate which will be used to get the _fromDate value of ViewSchedule.cs
    DateTime _toDate; ////Set a new variable of name _toDate which will be used to get the _toDate value of ViewSchedule.cs
    
    private void timer1_Tick(object sender, EventArgs e)
    {
        if (Form1.DateChanged) //Check if a change has been done recently
        {
            Form1.DateChanged = false; //Set the change to false so that the timer won't repeat
            _fromDate = Form1._fromDate; //Set our value of _fromDate from Form1._fromDate
            _toDate = Form1._toDate;//Set our value of _toDate from Form1._toDate
        }
    }
    

    This will set the values of Scheduler.cs to the new values from ViewSchedule.cs which I think is what you would like to achieve

    Thanks,
    I hope you find this helpful :)

提交回复
热议问题