This is my first attempt at learning classes in any language. I am trying to create a Windows Form Project that is a stop watch. I've created a class that has a StartClock method that starts a stopwatch, I then put the elapsed time into a timespan variable. I then take a elapsedTime string and set it equal to a formatted string with the time span varibles. Code Below.
public class CStopWatch
{
Stopwatch sw = new Stopwatch();
private DateTime startTime;
private DateTime stopTime;
private String elapsedTime;
public String ElapsedTime
{
get
{
return elapsedTime;
}
}
public String StartClock()
{
sw.Start();
TimeSpan ts = sw.Elapsed;
elapsedTime = String.Format("{0:00}:{1:00}:{2:00}",
ts.Hours, ts.Minutes, ts.Seconds / 10);
return elapsedTime;
}
public void StopClock()
{
// sw.Stop();
}
}
On the Windows Form I call a new instance of my CStopwatch class and then on the start button click event I start my forms timer, call my StartClock method, and then set my time interval to every second.
In my Timer tick event I set my label to display the elapsed time string variable. When I run this I do not get any errors, but the label does not change. Below is my Windows Form Code.
public partial class Form1 : Form
{
// string elapsedTime;
// public string elapsedTime { get { return elapsedTime; } }
CStopWatch sw = new CStopWatch();
public Form1()
{
InitializeComponent();
}
private void lblTime_Click(object sender, EventArgs e)
{
}
private void btnStart_Click(object sender, EventArgs e)
{
timer.Enabled = true;
sw.StartClock();
timer.Interval = 1000;
//Testing without using classes
/*
timer.Enabled = true;
sw.Start();
timer.Interval = 1000;
TimeSpan ts = sw.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}",
ts.Hours, ts.Minutes, ts.Seconds / 10);
*/
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer_Tick(object sender, EventArgs e)
{
lblTime.Text = sw.ElapsedTime;
}
}
I'm sure I'm missing something or doing something stupid, but all my google fu has not lead me to the answer yet. Thanks in advance.