Implement below class in your project.
public class StopWatch
{
private DateTime startTime;
private DateTime stopTime;
private bool running = false;
public void Start()
{
this.startTime = DateTime.Now;
this.running = true;
}
public void Stop()
{
this.stopTime = DateTime.Now;
this.running = false;
}
public double GetElapsedTime()
{
TimeSpan interval;
if (running)
interval = DateTime.Now - startTime;
else
interval = stopTime - startTime;
return interval.TotalMilliseconds;
}
public double GetElapsedTimeSecs()
{
TimeSpan interval;
if (running)
interval = DateTime.Now - startTime;
else
interval = stopTime - startTime;
return interval.TotalSeconds;
}
}
Now create instance (Page Level Variable) of StopWatch Class.
StopWatch myWatch = new StopWatch();
And call
myWatch.Start();
in button1_click and
myWatch.Stop();
in button2_click.
Use
myWatch.GetElapsedTimeSecs().ToString();
to display/get elapsed time.
In your ASPX code behind just add below changes
public partial class _Default : System.Web.UI.Page
{
static StopWatch sw;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
sw = new StopWatch();
}
Reason: every time in clicking on button it creates new instance of sw object. We are checking here for is not postback.
Regards
Rushi