Can anyone point me in the direction of C# code that would have a start/stop button that would record start to finish and then store that into a SQL table. It sounds pretty basic, but I am super new to C#. Any help appreciated.
Printable View
Can anyone point me in the direction of C# code that would have a start/stop button that would record start to finish and then store that into a SQL table. It sounds pretty basic, but I am super new to C#. Any help appreciated.
bump? no pointers?
Break the problem into pieces. First write the code that creates a start and stop button on a form and write the event handlers for each button.
Next, add the timer code and to get the timer to start on button start and stop the time when the button stop is pressed.
Finally, add the sql code to save the values into the database.
Which flavor of DB? MySQL? Postgres? MS SQL Server?
Also, here are some pointers: https://xkcd.com/138/
Here is my code so far. All I think I need is two fileds. The database is Microsoft SQL 2008 R2. I want two fields one with username and other with the end result of the timer. Timer is working, just need to assign to a database now :)
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Text;
namespace stopwatch
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class NextGenTimer : System.Windows.Forms.Form
{
DateTime da ;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Timer timer1;
private Label Ver;
private PictureBox pictureBox1;
private System.ComponentModel.IContainer components;
public NextGenTimer()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NextGenTimer));
this.label1 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.Ver = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// label1
//
this.label1.BackColor = System.Drawing.SystemColors.ControlLightLight;
this.label1.Font = new System.Drawing.Font("Harrington", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.Color.DarkBlue;
this.label1.Location = new System.Drawing.Point(16, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(224, 56);
this.label1.TabIndex = 0;
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.label1.Click += new System.EventHandler(this.label1_Click);
//
// button1
//
this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(178)));
this.button1.Location = new System.Drawing.Point(12, 78);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(223, 40);
this.button1.TabIndex = 1;
this.button1.Text = "Start";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// timer1
//
this.timer1.Interval = 1;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// Ver
//
this.Ver.AutoSize = true;
this.Ver.Location = new System.Drawing.Point(196, 153);
this.Ver.Name = "Ver";
this.Ver.Size = new System.Drawing.Size(44, 13);
this.Ver.TabIndex = 2;
this.Ver.Text = "Ver. 1.0";
//
// pictureBox1
//
this.pictureBox1.Image = global::stopwatch.Properties.Resources.next;
this.pictureBox1.Location = new System.Drawing.Point(1, 124);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(153, 41);
this.pictureBox1.TabIndex = 3;
this.pictureBox1.TabStop = false;
this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click);
//
// NextGenTimer
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.SystemColors.ScrollBar;
this.ClientSize = new System.Drawing.Size(254, 167);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.Ver);
this.Controls.Add(this.button1);
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "NextGenTimer";
this.Text = "StopWatch";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new NextGenTimer());
}
private void timer1_Tick(object sender, System.EventArgs e)
{
TimeSpan span = DateTime.Now.Subtract(da);
this.label1.Text = span.Hours.ToString() + " : " + span.Minutes.ToString() + " : " + span.Seconds.ToString() + " : "
+ span.Milliseconds.ToString();
}
private void button1_Click(object sender, System.EventArgs e)
{
if(this.timer1.Enabled)
{
timer1.Stop();
button1.Text = "Start";
}
else
{
da = DateTime.Now;
timer1.Start();
button1.Text = "Stop";
}
}
private void button2_Click(object sender, EventArgs e)
{
}
private void lnkReset_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
}
}
A typical sql insert would look like this. You can add as many parameters as needed and name them anything you want, and they can be of any datatype (I'm using strings here):
add using System.Data.SQLClient to your list of references
com.Paramters.Add(paramName,paramValue) can take any type of data (string, int, double, DateTime, etc) - the only time you need to worry about formatting or conversion is if your c-sharp datatype doesn't match your sql datatype for the same item. Basically, don't worry about it unless SQL throw an error.Code://your provider string may look something like this
string myProviderString = @"Data Source=WIN7-PC\MAINSQLSERVER2K8;Initial Catalog=Movies;Integrated Security=True";
void insertDBRecord(string thingOne, string thingTwo, string thingThree){
using(SQLConnection conn = new SQLConnection(myProviderString)){
SqlCommand com = conn.CreateCommand();
com.Parameters.AddWithValue("@thing1",thingOne);
com.Parameters.AddWithValue("@thing2",thingTwo);
com.Parameters.AddWithValue("@thing3",thingThree);
com.CommandText = "Insert into mytable (col1,col2,col3) values (@thing1,@thing2,@thing3)";
conn.Open();
com.ExecuteNonQuery();
conn.Close();
}
}
Hope this helps.
how can I change my button to "not" reset every time it is stopped. Meaning, I want to hit stop so the time is still there. Then create a second button to reset
I don't see where label1.Text (the timer) is changed. I'm guessing you want to leave the time in the label, so look for your stop button onclick event and follow the logic to see where it changes label1.text. change that line of code so that label1.text is left intact after the stop button is clicked.
well I'm still learning. I have an all in one button. Now they want a start button, stop button, and a reset button. Once I get that I need to start recording that data into SQL
Once you get all that done, repost your code and I'll help if you still have problems.
will do. Trying not to get my hand held the whole way through this.
If you can, please remove the debug and release folders from the source code, zip up the whole solution and post it here.
That way it's more convenient for folks trying to help - they just simply have to unzip and load the solution (instead of creating a new solution and pasting your code in).
How do I do that LOL? sorry I am new. I am just pasting the code on my screen in.
ON the other note: I am having issues separating the buttons ;)
Do you know how to zip up a program? If not, post back. Otherwise to post an attachment, in the Quick reply window, click "Go Advanced" and the click "Manage Attachments". From there you can upload your zipped file.
Before zipping be sure to remove the \debug and \release folders from the solution. The files in these folder only increase the size of the zip file and get recreated when you build, so there's no need in including them.
When you start on a project like this, I'd recommend that you work out the control states and logic first before adding the more complex features like the timer and database functionality.
What I like to do is create an enum that tells me what mode the form is in (start, stop, reset, etc.).
I then create button handlers to buttons and set the mode appropriate to the button. To make things easier, I set the control states (i.e whether a button or control is enabled/disabled) in one method and also call this method in each of the button handlers.
Using this approach you can very quickly set up what buttons and controls are enabled based on which button you click. You can also debug this very quickly because the all the enabling/disabling of controls is done in one method (and the method is simple).
See the attachment for the complete sln.Code:using System;
using System.Windows.Forms;
namespace CG.Timer
{
public partial class Form1 : Form
{
/// <summary>
/// Enum to track states
/// </summary>
private enum TimerMode
{
/// <summary>
/// Initial state when form opens
/// </summary>
Initial,
/// <summary>
/// State after reset button has been pressed
/// </summary>
Reset,
/// <summary>
/// State after start button has been pressed
/// </summary>
Start,
/// <summary>
/// State after stop button has been pressed
/// </summary>
Stop
}
public Form1( )
{
InitializeComponent( );
SetControlStates( );
}
#region Event Handlers
private void _start_Click( object sender, EventArgs e )
{
SetTimerMode( TimerMode.Start );
}
private void _stop_Click( object sender, EventArgs e )
{
SetTimerMode( TimerMode.Stop );
}
private void _reset_Click( object sender, EventArgs e )
{
SetTimerMode( TimerMode.Reset );
}
private void _cancel_Click( object sender, EventArgs e )
{
Close( );
}
private void _tbUserName_TextChanged( object sender, EventArgs e )
{
SetControlStates( );
_tbUserName.Focus( );
}
#endregion Event Handlers
#region Private Methods
/// <summary>
/// Sets the enabled/disabled control states based on the current timer mode.
/// </summary>
private void SetControlStates( )
{
_start.Enabled = false;
_stop.Enabled = false;
_reset.Enabled = false;
_tbUserName.Enabled = false;
switch ( _currentMode )
{
case TimerMode.Initial:
_start.Enabled = _tbUserName.TextLength > 0;
_tbUserName.Enabled = true;
break;
case TimerMode.Reset:
_start.Enabled = _tbUserName.TextLength > 0;
_tbUserName.Enabled = true;
break;
case TimerMode.Start:
_stop.Enabled = true;
break;
case TimerMode.Stop:
_reset.Enabled = true;
break;
}
}
private void SetTimerMode( TimerMode mode )
{
_currentMode = mode;
SetControlStates( );
}
#endregion Private Methods
private TimerMode _currentMode = TimerMode.Initial;
}
}
Tomorrow, I'll add the timer functionality.
In this version, I've added a timer and wired it up to the start/stop buttons as well as updated the status field on each timer click. I just format a string and have a _timerCount value that gets set to the status text.
To complete your project, I believe all you'll need to do is add your database saving code to the timer click (which is fine for a simple school project, but not how you would do it in the real world).
Code with timer added and updated Status field
See the attachment for the latest source.Code:using System;
using System.Windows.Forms;
namespace CG.Timer
{
public partial class Form1 : Form
{
/// <summary>
/// Enum to track states
/// </summary>
private enum TimerMode
{
/// <summary>
/// Initial state when form opens
/// </summary>
Initial,
/// <summary>
/// State after reset button has been pressed
/// </summary>
Reset,
/// <summary>
/// State after start button has been pressed
/// </summary>
Start,
/// <summary>
/// State after stop button has been pressed
/// </summary>
Stop
}
public Form1( )
{
InitializeComponent( );
SetControlStates( );
}
#region Event Handlers
private void _start_Click( object sender, EventArgs e )
{
SetTimerMode( TimerMode.Start );
}
private void _stop_Click( object sender, EventArgs e )
{
SetTimerMode( TimerMode.Stop );
}
private void _reset_Click( object sender, EventArgs e )
{
SetTimerMode( TimerMode.Reset );
}
private void _cancel_Click( object sender, EventArgs e )
{
Close( );
}
private void _tbUserName_TextChanged( object sender, EventArgs e )
{
SetControlStates( );
_tbUserName.Focus( );
}
private void _timer_Tick( object sender, EventArgs e )
{
_tbStatus.Text = String.Format("Running: {0}", _timerCount++);
// Add Database Call here.
}
#endregion Event Handlers
#region Private Methods
/// <summary>
/// Sets the enabled/disabled control states based on the current timer mode.
/// </summary>
private void SetControlStates( )
{
_start.Enabled = false;
_stop.Enabled = false;
_reset.Enabled = false;
_tbUserName.Enabled = false;
switch ( _currentMode )
{
case TimerMode.Initial:
_start.Enabled = _tbUserName.TextLength > 0;
_tbUserName.Enabled = true;
break;
case TimerMode.Reset:
_timerCount = 0;
_start.Enabled = _tbUserName.TextLength > 0;
_tbUserName.Enabled = true;
_tbStatus.Text = String.Empty;
break;
case TimerMode.Start:
_timerCount = 0;
_stop.Enabled = true;
_timer.Start();
break;
case TimerMode.Stop:
_reset.Enabled = true;
_timer.Stop( );
_tbStatus.Text = String.Format( "Stopped: {0}", _timerCount++ );
break;
}
}
private void SetTimerMode( TimerMode mode )
{
_currentMode = mode;
SetControlStates( );
}
#endregion Private Methods
private TimerMode _currentMode = TimerMode.Initial;
private long _timerCount;
}
}
yes I know how to zip. I can do that from here on out. I"ll check out your example.