Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to dynamically add radio buttons based on the height of the prvious radiobutton.

dim rbl as new radio button

 rb.Location = New Point(100, 300)
me.controls.add(rbl)


so lets say i add another radio button on to the form
rbl1.Location = New Point(100, 330)
me.controls.add(rbl1)

how do I go about using the height of the prvious radio buttons text to dynamically seperate the buttons.

What I have tried:

rbl1.Location = New Point(100, 330 + rbl.height)
but it overlaps the other rabiobuttons.
Posted
Updated 15-Jan-18 18:41pm

1 solution

Not clear how exactly the code is adding the radio button dynamically in to the form. Something not right with the maths. let assume the height is 24, here the output. You see the issue? The third one should be 330 + (2 * Height) ...

First control position (100, 330)
Second control position (100, 330 + 24)
Third control position (100, 330 + 24)
Fourth control position (100, 330 + 24)
...

Here an example. The code will first get the count of control added into the form, then call a method to create the RadioButton control by passing in the points and the control count.

VB
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim radioButtonList = Me.GetAllControls(Me).OfType(Of RadioButton)().ToList()
        Dim radioButtonCount As Integer = 1

        For Each item As RadioButton In radioButtonList
            If (item.Name.Contains("SomeDynamicRb")) Then
                radioButtonCount = radioButtonCount + 1
            End If
        Next

        If radioButtonCount = 0 Then
            radioButtonCount = 1
        End If

        AddRadiobutton(100, 100, radioButtonCount)

    End Sub

    Sub AddRadiobutton(ByVal x As Integer, ByVal y As Integer, ByVal count As Integer)
        Dim rbl As New RadioButton
        If (count = 1) Then
            rbl.Location = New Point(x, y)
        Else
            rbl.Location = New Point(x, y + ((count - 1) * rbl.Height))
        End If

        rbl.Text = "Radio Button " + count.ToString()
        rbl.Name = "SomeDynamicRb_" + count.ToString()
        Me.Controls.Add(rbl)
    End Sub

    Private Function GetAllControls(control As Control) As IEnumerable(Of Control)
        Dim controls = control.Controls.Cast(Of Control)()
        Return controls.SelectMany(Function(ctrl) GetAllControls(ctrl)).Concat(controls)
    End Function


.net - How to get all TextBox controls of a Form - Stack Overflow[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900