假设我有两个按钮btnCheck和btnOK。我想从btnOK执行btnCheck的几行代码。所以当我点击btnOK时,btnOK的代码以及BtnCheck的代码应该一个接一个地执行。我怎么能在vb.net中做到这一点
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
..................................
..............CODES 1.............
..................................
.........CODES FROM BtnCheck......
..................................
End Sub
Private Sub btnCheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheck.Click
..................................
..............CODES 2...............
..................................
End Sub
[可以使用Goto吗? ]
答案 0 :(得分:1)
我想你问的是如何在这两个程序之间共享一些代码。那么为什么不能这样:
Private Sub btnOK_Click(...)
sharedSubroutine(...)
Private Sub btnCheck_Click(...)
sharedSubroutine(...)
Private Sub sharedSubroutine(...)
'Here is the shared code
换句话说,您创建一个新的子例程/过程/函数,其中包含前两个之间通用的代码,并且您从btnCheck_Click和btnOK_Click调用此新代码。
答案 1 :(得分:1)
除了按照建议制作单独的程序外,如果要运行其所有代码,也可以简单地调用另一个子程序:
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
'...
btnCheck_Click(sender, e) 'This will run the btnCheck code
End Sub
Private Sub btnCheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheck.Click
'...
End Sub
尽量避免在代码中使用goto
,但使用其他控制结构几乎总是有更好的方法。
答案 2 :(得分:0)
希望这会有所帮助
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click, btnCheck.Click
dim s as string = sender.name
if s = "btnOK" then code(1) :exit sub '//this will triger code1 and code 2
if s = "btnCheck" then code(2) :exit sub '//this will trigger code2 alone
End Sub
sub Code(x as integer)
if x = 1 then code1 & code2 : exit sub
if x = 2 then code2 : exit sub
end sub