Question

I need to create a button that makes two events and saves it into database (arrival and departure time of employee).

What i need to do First click on button saves arrival time of employee to database, Second click on same button saves departure time of employee (instead of having 2 buttons ofcourse)

I think i need some kind of counter that counts button clicks, or something like that, but i really have no clue how to program sth like that, so if you could please help me out.

This is what i have so far Please notice that the code does not work, so there is no problem except for me not knowing how to program it. Thank you

int counter = 0;
    public void button1_Click(object sender, EventArgs e)
    {
        counter++;
        try
        {
            if (counter == 1)
            {

                OleDbConnection myConnection= new OleDbConnection("\\CONNECTION PATH");
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = myConnection;
                cmd.CommandText = "Insert into Weekdays (Arrival)" + "values(@Arrival)";

                cmd.Parameters.AddWithValue("@Arrival", DateTime.Now);

                myConnection.Open();
                cmd.ExecuteNonQuery();
                MessageBox.Show("Arrival added.");
                myConnection.Close();

            }
            else if (counter == 2)
            {
                OleDbConnection myConnection= new OleDbConnection("\\CONNECTION PATH");
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = myConnection;
                cmd.CommandText = "Insert into Weekdays (Departure)" + "values(@Departure)";

                cmd.Parameters.AddWithValue("@Departure", DateTime.Now);

                myConnection.Open();
                cmd.ExecuteNonQuery();
                MessageBox.Show("Departure added.");
                myConnection.Close();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
Was it helpful?

Solution

You could create a bool to indicate whether the employee is clocked in yet or not.

bool clockedIn = false;

public void button1_Click(object sender, EventArgs e)
{
    if (!clockedIn)
    {
        // employee just arrived - log arrival time
    }
    else
    {
        // employee leaving - log departure time
    }

    clockedIn = !clockedIn;
}

OTHER TIPS

Quick and dirty way:

    private void button1_Click(object sender, EventArgs e)
    {
        if (button1.Tag == null)
        {
            button1.Tag = "toogled";

            // run event 1
        }
        else
        {
            button1.Tag = null;

            // run event 2
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top