2016-03-07 54 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」];

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