5

我想编写一个在我单击它时button以编程方式单击另一个的代码。button

例如,我有两个名为Button1and的按钮Button2,我想做的是在单击 后立即Button1单击Button2。这可能吗?

4

5 回答 5

16

最佳实施取决于您要尝试做什么。Nadeem_MK 给你一个有效的。知道您还可以:

  1. 使用方法引发Button2_Click事件PerformClick()

    Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        'do stuff
        Me.Button2.PerformClick()
    End Sub
    
  2. 将相同的处理程序附加到许多按钮:

    Private Sub Button1_Click(sender As Object, e As System.EventArgs) _
        Handles Button1.Click, Button2.Click
        'do stuff
    End Sub
    
  3. Button2_Click使用与方法相同的参数调用方法Button1_Click(...)(例如,如果您需要知道哪个是发送者):

    Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        'do stuff
         Button2_Click(sender, e)
    End Sub
    
于 2013-10-03T06:05:22.830 回答
14
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Button2_Click(Sender, e)
End Sub

此代码以编程方式调用按钮单击事件

于 2013-10-03T05:40:50.230 回答
5

这种情况的最佳实践是创建一个包含所有逻辑的方法,并在两个事件中调用该方法,而不是从另一个事件中调用一个事件;

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        LogicMethod()

End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        LogicMethod()

End Sub

Private Sub LogicMethod()

     // All your logic goes here

End Sub

如果您需要 EventArgs (e) 的属性,您可以轻松地通过方法中的参数传递它,如果发送者属于不同类型,这将避免错误。但这在您的情况下不会成为问题,因为两个发件人都是 Button 类型。

于 2013-10-03T05:48:55.387 回答
2

假设按钮 1 有一个名为的事件

Button1_Click(Sender, eventarg)

如果你想在 Button2 中调用它,那么直接调用这个函数。

Button1_Click(Nothing, Nothing)
于 2013-10-03T05:36:32.657 回答
0

在 c# 中这是有效的:D

protect void button1_Click(object sender, EventArgs e){
    button2_Click(button2, null);
}

protect void button2_Click(object sender, EventeArgs e){
    //some codes here
}

对于 vb.net

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)   Handles Button1.Click
    Button2_Click(Sender, e)
End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)   Handles Button2.Click
    //some codes here
End Sub
于 2013-10-03T05:43:16.833 回答