我想编写一个在我单击它时button
以编程方式单击另一个的代码。button
例如,我有两个名为Button1
and的按钮Button2
,我想做的是在单击 后立即Button1
单击Button2
。这可能吗?
最佳实施取决于您要尝试做什么。Nadeem_MK 给你一个有效的。知道您还可以:
使用方法引发Button2_Click
事件PerformClick()
:
Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
'do stuff
Me.Button2.PerformClick()
End Sub
将相同的处理程序附加到许多按钮:
Private Sub Button1_Click(sender As Object, e As System.EventArgs) _
Handles Button1.Click, Button2.Click
'do stuff
End Sub
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
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Button2_Click(Sender, e)
End Sub
此代码以编程方式调用按钮单击事件
这种情况的最佳实践是创建一个包含所有逻辑的方法,并在两个事件中调用该方法,而不是从另一个事件中调用一个事件;
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 类型。
假设按钮 1 有一个名为的事件
Button1_Click(Sender, eventarg)
如果你想在 Button2 中调用它,那么直接调用这个函数。
Button1_Click(Nothing, Nothing)
在 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