开发者

how to execute part of the code in an another sub procedure

开发者 https://www.devze.com 2023-03-01 12:17 出处:网络
Suppose I have two buttons btnCheck and btnOK. I want to execute few lines code of btnCheck from btnOK. So that When I click on btnOK, btnOK\'s code as well as BtnCheck\'s Code should be executed one

Suppose I have two buttons btnCheck and btnOK. I want to execute few lines code of btnCheck from btnOK. So that When I click on btnOK, btnOK's code as well as BtnCheck's Code should be executed one after the other. How can I do this in 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 btnChec开发者_运维知识库k_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheck.Click
..................................
..............CODES 2...............
..................................
End Sub

[ Can it be done using Goto ? ]


In addition to making a separate procedure as has been suggested, you can also simply call the other sub if you want to run all of its code:

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

Try to avoid using goto in your code if at all possible, there's nearly always a better way using other control structures.


I think you're asking how to share some code between these two procedures. So why not something like:

Private Sub btnOK_Click(...)
    sharedSubroutine(...)

Private Sub btnCheck_Click(...)
    sharedSubroutine(...)

Private Sub sharedSubroutine(...)
    'Here is the shared code

In other words, you create a new subroutine/procedure/function that contains the code that is common between your first two, and you call this new code from both btnCheck_Click and also btnOK_Click.


Hope this helps

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号