User59
User59

Reputation: 517

Event handling for dynamically created object in vb.net

I am creating dynamic objects on a windows form, so far i have managed to create objects such as labels and radio buttons dynamically. However, now i am struggling with the event handling process. I know that i have to use AddressHandler and AddressOf ( as you can see from the code below)

Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click

    Dim i As Integer
    Dim radi As RadioButton
    For i = 1 To 4
        radi = New RadioButton
        radi.Location = New System.Drawing.Point(j, n)
        n = n + 60
        radi.Text = List(i)
        radi.Name = "rad" & i

        Me.Controls.Add(radi)
        AddHandler radi.CheckedChanged, AddressOf Me.RadioButton_Checked
    Next

End Sub
Private Sub RadioButton_Checked(ByVal sender As System.Object, ByVal e As System.EventArgs)
    If TypeOf sender Is RadioButton Then

    End If
    End If
End Sub

I need the code to output a message box in the case the user selects a specific option from the radio boxes. For example if they select "true" a msgbox should pop up.

Can someone give me some guidance on merely getting the code to recognise that the user has selected a radio button and to recognise the text of the radiobutton e.g. "true" , "wrong" etc.

Thanks in advance.

If you need any more clarification just ask.

Upvotes: 1

Views: 1007

Answers (2)

Behrooz
Behrooz

Reputation: 1734

You can use the Tag property and set it to some value that can help you identify the control with later.

radi.Tag = 1

and then

Dim radi as RadioButton = CType(sender, RadioButton)
if radi.Tag = 1 Then

End If

Upvotes: 1

LarsTech
LarsTech

Reputation: 81620

Try casting the sender:

With DirectCast(sender, RadioButton)
  If .Checked Then
    'Do Something
  End If
End With

Upvotes: 1

Related Questions