Failed_Noob
Failed_Noob

Reputation: 1357

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

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 btnCheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheck.Click
..................................
..............CODES 2...............
..................................
End Sub

[ Can it be done using Goto ? ]

Upvotes: 3

Views: 11123

Answers (3)

Joan Bacalso
Joan Bacalso

Reputation: 1

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

Upvotes: 0

Flash
Flash

Reputation: 16753

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.

Upvotes: 1

Henry
Henry

Reputation: 6620

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.

Upvotes: 1

Related Questions