Ljutgu Las Ljutgu Las - 11 months ago 76
Vb.net Question

vb TableLayoutPanel - Getting button next to the button clicked

I created a simple TableLayoutPanel (6 by 6) with buttons in each cell. I have a click handler that executes whenever any of the button is pressed (in my case, change color of the button from red to green)

see eg.

But now I need to change the color of the button next to the button i clicked (eg. When I click on button 2 3, the button 3 3 will also change color).

Any ideas?

Answer Source

You can cast the Sender argument on the click handler to a Control and then use that to determine the clicked control's position. Then you can use that position to compute you adject controls and retrieve a reference to them.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim ctrl As Control = TryCast(sender, Control)
    If ctrl IsNot Nothing Then
        Dim pos As TableLayoutPanelCellPosition = TableLayoutPanel1.GetCellPosition(ctrl)
        If pos.Row < (TableLayoutPanel1.RowCount - 1) Then
            Dim nextCtrl As Control = TableLayoutPanel1.GetControlFromPosition(pos.Column, pos.Row + 1)
            If nextCtrl IsNot Nothing Then
                ' do something with nextCtrl
                nextCtrl.BackColor = Color.Red
            End If
        End If
    End If
End Sub