Passing variable (time) from one form to another C#

时光毁灭记忆、已成空白 提交于 2019-12-01 13:46:36

Pass start time to second form

private void StartButton_Click(object sender, EventArgs e)
{
    Form2 frm = new Form2(DateTime.Now);
    frm.Show();
    this.Hide();
}

And then use it

public partial class Form2 : Form
{
    private DateTime startTime;

    public Form2(DateTime startTime)
    {
        InitializeComponent();
        this.startTime = startTime;
    }

    private void StopButton_Click(object sender, EventArgs e)
    {
        endTime = DateTime.Now;
        ts_timeElapsed = (endTime - startTime);
        s_timeElapsed = GetElapsedTimeString();
        ElapsedLabel.Text = "Time Elapsed: " + s_timeElapsed;

        Form3 frm = new Form3();
        frm.Show();
    }     
}

Depending on if these forms exist within the same application, you could pass a reference to the first form into the second. And then (because the starttime1 DateTime object is public, you can access it from the second form.

It would be cleaner and more maintainable if stored the data in a place that is accessible from both forms. For example a static class. (You could also use a database or text file)

public static TempStore
{
    public DateTime StartTime { get; set; }
}

Set StartTime from From1 and read back the difference in Form2

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

    private void StartButton_Click(object sender, EventArgs e)
    {
        TempStore.StartTime = DateTime.Now;

        // ...
    }
}

Form 2:

public partial class RoadSign1Meaning : Form
{
    public RoadSign1Meaning()
    {
        InitializeComponent();
    }

    private void StopButton_Click(object sender, EventArgs e)
    {
        TimeSpan span = DateTime.Now - TempStore.StartTime;             

        // ...
    }
}

This way, if you decide to pass more data to and from forms you can extend this static class.

There are several solutions but also depends on the complexity of what would you like to achieve. The simplest one with less modifications in your code would be to declare a constructor on your second form which accepts a parameter of type DateTime and pass in startTime2 from Form1 when creating the Form2 just like Form2 form2 = new Form2(startTime2). A more elegant way would be to define an interface with a method GetElapsedTime() and create a concrete in which takes care of the start/end time and you can pass the concrete instance to Form2 like before from Form1.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!