Code Generated Radio Button Issue
I am using VB.Net to create one radiobutton for each line in a text file.
Code:
For i = 0 To SFLines.Length - 1
SRadioButton = New RadioButton
With SRadioButton
.Text = SFInfo(i, 1) & ", " & SFInfo(i, 0)
.Location = New Point(10, ((i + 1) * 17))
.Size = New Size(180, 17)
.Name = "RadioButton" & i
Me.grpSRadio.Controls.Add(SRadioButton)
End With
Next
SFLines is the number of lines in the text files. SFInfo is an array that is created using a Split on each line. The code works fine and my group populates with all the radio buttons. The issue is with the .Checked of the radio buttons created. Because the radio buttons are created in the forms on load event I cannot add code that references the radio button. VB.Net states that the Name RadioButtonX is not defined.
Here is what I tried to do:
Code:
Private Sub btnSelect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelect.Click
Dim i
Dim SRadioButton As New RadioButton
For i = 0 To SFLines.Length - 1
SRadioButton.Name = "RadioButton" & i
If SRadioButton.Checked = True Then
MsgBox(SRadioButton.Text)
End If
Next
End Sub
This does not work.
I need a Select button that will display some info about the array element based on the radio button selected.
Any help would be greatly appreciated.
Re: Code Generated Radio Button Issue
Use this code:
vb.net Code:
Private Sub btnSelect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelect.Click
Dim i As Integer
Dim sRadioButton As RadioButton
For i = 0 To SFLines.Length - 1
If TypeOf Me.grpSRadio.Controls("RadioButton" & i) Is RadioButton Then
sRadioButton = DirectCast(Me.grpSRadio.Controls("RadioButton" & i), RadioButton)
If sRadioButton.Checked Then
MessageBox.Show(sRadioButton.Text)
End If
End If
Next
End Sub
Re: Code Generated Radio Button Issue
Thanks for the help, I'll have to try and see if that works. After playing with some code I found that is was easier to create a control array of radio buttons and evaluate the value of each element in the array so that if the element = -1 that is the selected radiobutton.
Re: Code Generated Radio Button Issue
Assuming you're using .NET 3.5, here's the easiest way to find the checked RadioButton:
vb.net Code:
Dim checkedItem As RadioButton = Me.grpSRadio.Controls.OfType(Of RadioButton).Where(Function(rb As RadioButton) rb.Checked).First()
That's LINQ function syntax that gets all RadioButtons from the Controls collection where the Checked property is True, then returns the first one of them.
Re: Code Generated Radio Button Issue
Here's the LINQ query syntax equivalent, which some may find easier to understand as it doesn't use an explicit lambda expression:
vb.net Code:
Dim checkedItem As RadioButton = (From rb In Me.grpSRadio.Controls.OfType(Of RadioButton)() _
Where rb.Checked).First()