从另一个函数vb.net调用控制方法

时间:2013-11-27 18:42:08

标签: vb.net

我想知道是否可以使用与另一个函数的控件关联的方法。例如

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

2 个答案:

答案 0 :(得分:1)

假设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

答案 1 :(得分:0)

通常明智的做法是将事件中的代码限制为处理与用户相关的事物。您可以将公共代码放在subs中,并从事件,其他方法(Subs)和其他函数中调用它们:

  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

这可以防止应用程序逻辑(业务/ Web等等)无法混合,甚至依赖于UI层和当前布局。注意:一些控件实现了一种调用事件代码的方法:例如按钮和无线电具有btn.PerformClick,没有复选框的运气。