单击一次按钮可创建两个事件

时间:2014-01-14 17:28:23

标签: c# database connection oledbconnection oledbcommand

我需要创建一个按钮,生成两个事件并将其保存到数据库中(员工的到达和离开时间)。

我需要做什么首先点击按钮可以将员工的到达时间保存到数据库中,再次点击相同的按钮可以节省员工的出发时间(而不是2个按钮) ofcourse)

我想我需要某种计数器来计算按钮点击次数,或类似的东西,但我真的不知道如何编程这样,所以如果你能帮我解决。

这是我到目前为止请注意代码不起作用,所以除了我不知道如何编程之外没有问题。谢谢

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);
        }
    }

2 个答案:

答案 0 :(得分:1)

快速而肮脏的方式:

    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
        }
    }

答案 1 :(得分:1)

您可以创建一个bool来指示员工是否已经开启。

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;
}