如何在按钮单击事件处理程序之间切换

时间:2013-10-16 07:42:24

标签: c# events event-handling desktop-application

我正在创建一个添加/编辑用户的桌面应用程序。这两个函数都将使用相同的输入,但是每个函数都需要不同的点击处理程序来更新数据并将新数据插入到我的数据库中,但我想使用相同的按钮

他们是否可以将不同的点击处理程序分配到同一个按钮?

2 个答案:

答案 0 :(得分:0)

是的,你可以,

//Register both handlers within constructor
button1.Click += new EventHandler(InsertOperationHandler);
button1.Click += new EventHandler(UpdateOperationHandler);

-

private void InsertOperationHandler(object sender, EventArgs e)
{

}


private void UpdateOperationHandler(object sender, EventArgs e)
{

}

答案 1 :(得分:0)

我想出的解决方案如下:

public void displayEditButtons()
{
    buttonPeopleOne.Text = "Save Changes";
    this.buttonPeopleOne.Click -= new System.EventHandler(this.buttonPeopleOneClear_Click);
    this.buttonPeopleOne.Click += new System.EventHandler(this.buttonPeopleOneSave_Click);

        buttonPeopleTwo.Text = "Delete User";
        this.buttonPeopleTwo.Click -= new System.EventHandler(this.buttonPeopleTwoNext_Click);
        this.buttonPeopleTwo.Click += new System.EventHandler(this.buttonPeopleTwoDelete_Click);

        //change other controls to match the function context
        buttonPeopleChangeFunction.Visible = true;
        this.labelPeopleFunctionHeader.Text = "Edit Current User";
    }

    public void displayAddButtons()
    {
        buttonPeopleOne.Text = "Clear";
        this.buttonPeopleOne.Click -= new System.EventHandler(this.buttonPeopleOneSave_Click);
        this.buttonPeopleOne.Click += new System.EventHandler(this.buttonPeopleOneClear_Click);


        buttonPeopleTwo.Text = "Add Contact";
        this.buttonPeopleTwo.Click -= new System.EventHandler(this.buttonPeopleTwoDelete_Click);
        this.buttonPeopleTwo.Click += new System.EventHandler(this.buttonPeopleTwoNext_Click);

        //change other controls to match the function context
        buttonPeopleChangeFunction.Visible = false;
        this.labelPeopleFunctionHeader.Text = "Add New User";

}

当我需要更改按钮时,我只需调用不同的方法