Home > other >  Is there a Dynamic Solution to this that someone might be able to explain?
Is there a Dynamic Solution to this that someone might be able to explain?

Time:12-29

Ref: There are 20ish panels that need this event at visibility change, all with the same naming conventions being project_x (x being the panel number)

I'm not able to do an expectation vs reality on this code because I was not able to find how to best do this.

Further Explanation: On the event 'VisibleChanged' Which is controlled by an External Class, We want a way to apply this dynamically in a shorter code. Sure we can do this and hard code everything in and it works fine, but I was wondering if there was a way to do this dynamically.

Private Sub project_1_VisibleChanged(sender As Object, e As EventArgs) Handles project_1.VisibleChanged
        Try
            If project_1.Visible = True Then
               'There's code here but it's been omitted
            End If
        Catch ex As Exception
        End Try
    End Sub

CodePudding user response:

You can find all relevant panels in form load and subscribe each to a single event handler method

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    'assuming the panels are on the main form you would use Me
    'else you would use the name of the control that the panel is located within - e.g. SomeControlName.Controls...
    Dim panels = Me.Controls.OfType(Of Panel).Where(Function(panel) panel.Name.StartsWith("project_"))

    For Each panel In panels
        AddHandler panel.VisibleChanged, AddressOf PanelVisibilityChanged
    Next
End Sub

Private Sub PanelVisibilityChanged(sender As Object, e As EventArgs)
    Dim panel = DirectCast(sender, Panel)

    Try
        If panel.Visible Then
            'assuming the picture box is within the panel
            Dim pictureBox = panel.Controls.Find($"{panel.Name}_img", True)(0)
            'There's code here but it's been omitted
        End If
    Catch ex As Exception
    End Try
End Sub

CodePudding user response:

Yes, like this:

Private Sub panels_VisibleChanged(sender As Object, e As EventArgs) _
  Handles project_1.VisibleChanged,
          project_2.VisibleChanged,
          project_3.VisibleChanged,
          project_4.VisibleChanged,
          project_5.VisibleChanged,
          project_6.VisibleChanged,
          project_7.VisibleChanged
    Dim ctrl As Panel = DirectCast(sender, Panel)
    Try
        If ctrl.Visible = True Then
           'There's code here but it's been omitted
        End If
    Catch ex As Exception
    End Try
End Sub

There are a couple of other ways to do this as well. This is probably the cleanest for VB.net and your situation.

  • Related