There is no automatic way in Windows Forms to do what you want, as the logic which makes the radio buttons enclosed in one Panel or GroupBox behave like radio buttons seems to be tied to them being added during design time already.
But you could work around that pretty easily. Set the radio button AutoCheck
property to False
, so that it does not try to do anything special for you. Then listen for the clicked event in your container class and whenever one of the buttons is clicked, go through them all, checking the one which was clicked, unchecking the rest of them.
It works for me like this -- I even got rid of MyRadioButton
for simplicity, as it was not required anymore:
MyRadioGroupBox.vb
Public Class MyRadioGroupBox
Inherits UserControl
Public Sub New(ByVal grpBoxName As String, ByVal controlValues As Array, _
ByVal construct As Object)
InitializeComponent()
Me.GroupBox.Text = grpBoxName
For i As Integer = 0 To controlValues.Length - 1
' Create a regular RadioButton
Dim myRdn As RadioButton = New RadioButton
myRdn.Text = controlValues.GetValue(i)
myRdn.AutoSize = True
' Disable its AutoCheck functionality
myRdn.AutoCheck = False
myRdn.Dock = DockStyle.Fill
Me.FlowLayoutPanel1.Controls.Add(myRdn)
' Register for its Click event
AddHandler myRdn.Click, AddressOf MyRadioGroupBox_rdnBtnClicked
Next
End Sub
Private Sub MyRadioGroupBox_rdnBtnClicked(sender As Object, e As EventArgs)
' For all child controls in the panel...
For Each oControl As Object In FlowLayoutPanel1.Controls
' ...get it as a RadioButton and compare with the event sender,
' i.e. the button which has just been clicked.
Dim myRdn As RadioButton = oControl
If Object.ReferenceEquals(myRdn, sender) Then
' Match - it's the one which has just been clicked, check it
myRdn.Checked = True
Else
' Does not match - it's some other one, uncheck it
myRdn.Checked = False
End If
Next
End Sub
End Class