Kyle Trainor
Kyle Trainor

Reputation: 3

Call a control method from another function vb.net

I am wondering if it is possible to use the method associated with a control from another function. For example

Sub myCheckBox(sender As Object, e As EventArgs) Handles myCheckBox.CheckedChanged
'''Code I want to run from other function
End Sub

Function MyOtherFunction(x as double, y as double) as double
'''Call myCheckBox method
End function

Upvotes: 0

Views: 1456

Answers (2)

It is generally wise to limit code in events to handling user related things. You can place common code in subs and call them from events, other methods (Subs) and other functions:

  Sub myCheckBox(sender As Object, e As EventArgs) Handles myCheckBox.CheckedChanged
     ' user / click related code
     ' ...
     CommonReusableCodeSub(sender As object)
  End Sub

  Function MyOtherFunction(x as double, y as double) as double
     ' do some special stuff, maybe even just to prep
     ' for the call to a common sub
     CommonReusableCodeSub(Nothing)
  End function

  Sub CommonReusableCodeSub(chk as CheckBox) ' can also be a function
      ' do stuff common to both above situations

      ' note how to detect what is going on:
      If chk Is Nothing then
         ' was called from code, not event
         ' do whatever
         Exit Sub      ' probably
      End If

      Select Case chk.Name     ' or maybe chk.Tag
          chk.thisOption
            ' do whatever
          chk.thatOption
            ' do whatever
          ' etc...
       End Select

  End Sub

This prevents app logic (business/web etc etc etc ) from getting hopelessly intermingled and even dependent upon the UI layer and current layout. Note: some controls implement a way to call event code: buttons and radios for instance have a btn.PerformClick, no such luck with checkboxes.

Upvotes: 0

OneFineDay
OneFineDay

Reputation: 9024

Assuming WinForms:

Dim cbs = Me.Controls.OfType(Of Checkbox)().Where(Function(cb) cb.Checked).ToList()
For Each cb In cbs
  'run code for each checkbox that is checked
Next

Upvotes: 1

Related Questions