TimeSpan仍然无法正常工作

时间:2014-03-10 13:18:45

标签: c# asp.net webforms session-state timespan

下面是我安排的代码,但仍有同样的问题,无法在最后一页找到我的开始和结束时间?我该怎么做?

public void start()
    {
        DateTime startTime = DateTime.Now;
    }

    protected void btnStart_Click(object sender, EventArgs e)
    {
        start();
        Response.Redirect("~/end.aspx");
    }

public void end()
    {
        DateTime endTime = DateTime.Now;
    }
    protected void btnEnd_Click(object sender, EventArgs e)
    {
        end();
        Response.Redirect("~/display.aspx");
    }

public partial class display : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        TimeSpan timeSpent = endTime - startTime;

        lblDisplay.Text = string.Format("Time: {0}", timeSpent);
    }
}

现在有人可以帮我吗?我应该使用会话,如果我应该,我如何使用它与日期时间和时间跨度等等。谢谢!

1 个答案:

答案 0 :(得分:2)

问题:您在函数中声明了startTimeendTime个变量,如下所示:

public void start()
{
    DateTime startTime = DateTime.Now; //remove the declartion from here
}

public void end()
{
    DateTime startTime = DateTime.Now; //remove the declaration from here
}

解决方案:将您的startTimeendTime变量声明为类变量,然后在start()end()函数中指定值。< / p>

试试这个:

DateTime startTime; //declare here
DateTime endTime;   //declare here

public void start()
{
    startTime = DateTime.Now; //assign value here
}
public void end()
{
    endTime = DateTime.Now;  //assign value here
}