Tan Pinzhi
Tan Pinzhi

Reputation: 5

Get panel from button inside and change TableLayoutPanel cell color

I have a TableLayoutPanel, panel in each cell, 2 RadioButton in each panel. When I checked the RadioButton, the cell color will change. I know I can do it with assign CheckedChanged event to each RadioButton and hardcode the cell row and column to change the color. I have 15 panels, so will have 30 different CheckedChanged event.

Is there any way that I can use the sender(RadioButton) to get its panel? So that I can use GetCellPosition(panel) to get the cell and use the panel to get which RadioButton in it is checked. Then I can just assign this event to all RadioButtons.

Upvotes: 0

Views: 30

Answers (1)

41686d6564
41686d6564

Reputation: 19641

That can be achieved by using the Control.Parent property.

Your code should look something like this:

Private Sub RBs_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged,
                                                                         RadioButton2.CheckedChanged,
                                                                         ' ...etc.
    Dim rb = DirectCast(sender, RadioButton)
    Dim pnl = DirectCast(rb.Parent, Panel)
    
    ' TODO: Do something with pnl and/or rb.
    Console.WriteLine(pnl.Name)
End Sub

Do note, however, that selecting a certain RadioButton will trigger the CheckedChanged event for two RBs; the one that got checked and the one the got unchecked. So, you might want to wrap your code inside If rb.Checked Then ... End If or whatever is appropriate.

Upvotes: 1

Related Questions