简体   繁体   中英

Passing data from one button click event to another button click event

Below is my code. I want to capture the difference between two timestamps at two different button clicks, ie, i want the "startTime" of btnStartTime_click event to be used in btnEndTime_click event.

    protected void btnStartTime_Click(object sender, EventArgs e)
    {
        var startTime = DateTime.Now;            
        lblStartTime.Text = startTime.ToString("HH:mm:ss tt");            
    }

    protected void btnEndTime_Click(object sender, EventArgs e)
    {            
        var workDuration = DateTime.Now.Subtract(startTime).TotalMinutes;
        lblEndTime.Text = ("The Work duration is "+workDuration);

    }

Just make your startTime outside the local scope:

DateTime startTime;
protected void btnStartTime_Click(object sender, EventArgs e)
{
    startTime = DateTime.Now;            
    lblStartTime.Text = startTime.ToString("HH:mm:ss tt");            
}

protected void btnEndTime_Click(object sender, EventArgs e)
{            
    var workDuration = DateTime.Now.Subtract(startTime).TotalMinutes;
    lblEndTime.Text = ("The Work duration is "+workDuration);

}

Since this concerns a web application, you must store the startTime in a way where it can be restored on a later post back.

Here's a quick sample that should work using ViewState :

private const string StartTimeViewstateKey = "StartTimeViewstateKey";
protected void btnStartTime_Click(object sender, EventArgs e)
{
    var startTime = DateTime.Now;
    ViewState[StartTimeViewstateKey] = startTime.ToString(CultureInfo.InvariantCulture);
}
protected void btnEndTime_Click(object sender, EventArgs e)
{
    var startTime = DateTime.Parse((string)ViewState[StartTimeViewstateKey], CultureInfo.InvariantCulture);

    var workDuration = DateTime.Now.Subtract(startTime).TotalMinutes;
    lblEndTime.Text = ("The Work duration is " + workDuration);
}

Alternatively you could use session state:

private const string StartTimeSessionKey= "StartTimeSessionKey";
protected void btnStartTime_Click(object sender, EventArgs e)
{
    var startTime = DateTime.Now;
    Session[StartTimeSessionKey] = startTime;
}
protected void btnEndTime_Click(object sender, EventArgs e)
{
    var startTime = (DateTime)Session[StartTimeSessionKey];

    var workDuration = DateTime.Now.Subtract(startTime).TotalMinutes;
    lblEndTime.Text = ("The Work duration is " + workDuration);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM