2016-03-07 58 views
1

我是ASP.NET的新手,我试图从页面加载时间到时间点击按钮结束会话时查找会话持续时间。我试图使用DateTime和TimeSpan,但问题是在一个事件中生成的DateTime值无法在其他事件中访问。在ASP.NET C中的会话持续时间#

'// Code 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

namespace WebApplication17 
{ 
public partial class WebForm1 : System.Web.UI.Page 
{ 
    //DateTime tstart, tnow, tend; 


    protected void Page_Load(object sender, EventArgs e) 
    { 


    } 

    // Button to Start the Session 
    public void begin_Click(object sender, EventArgs e) 
    { 
     DateTime tstart = DateTime.Now; 
     SesStart.Text = tstart.ToString(); 
    } 

    // To Display the Present Time in UpdatePanel using AJAX Timer 
      protected void Timer1_Tick(object sender, EventArgs e) 
    { 
     DateTime tnow = DateTime.Now; 
     PresTime.Text = tnow.ToString(); 

    } 

    // Button to end the Session 
    public void end_Click(object sender, EventArgs e) 
    { 
     DateTime tend = DateTime.Now; 

    //The Problem exists here. the value of tstart is taken by default as     
     TimeSpan tspan = tend - tstart; 


     SesEnd.Text = tend.ToString(); 
     Dur.Text = Convert.ToString(tstart); 

      } 
     } 
    }' 

回答

0

您需要保存开始时间在会议

// Button to Start the Session 
public void begin_Click(object sender, EventArgs e) 
{ 
    DateTime tstart = DateTime.Now; 
    SesStart.Text = tstart.ToString(); 
    Session["StartTime"] = tStart; 
} 

,并用它在你的end_Click

// Button to end the Session 
public void end_Click(object sender, EventArgs e) 
{ 
    DateTime tend = DateTime.Now; 
    var tstart = Session["StartTime"] as DateTime; // see this      
    TimeSpan tspan = tend - tstart; 
    SesEnd.Text = tend.ToString(); 
    Dur.Text = Convert.ToString(tstart); 
} 
1

您可以使用Session变量来解决这个问题。您需要在调用begin_Click事件时设置会话变量值。

public void begin_Click(object sender, EventArgs e) 
{ 
    DateTime tstart = DateTime.Now; 
    SesStart.Text = tstart.ToString(); 
    Session["BeginEnd"] = tstart; 
} 

,并点击end_Click的时间做到这一点

public void end_Click(object sender, EventArgs e) 
{ 
    DateTime tend = DateTime.Now; 
    DateTime tstart = Convert.ToDateTime(Session["BeginEnd"]); 
    TimeSpan tspan = tend - tstart; 
    SesEnd.Text = tend.ToString(); 
    Dur.Text = Convert.ToString(tstart); 
} 
0

使用Session是这里最好的办法。由于您的页面被回传,所以它会丢失任何临时保留值。

  1. on开始创建会话[“time1”] = DateTime.Now;
  2. 停止从会话中检索值DateTime dt = Session [“time1”];

让我知道你是否需要其他任何澄清。