Results 1 to 18 of 18

Thread: [RESOLVED] Using arrays to add information to radio buttons/checkboxes on a form

  1. #1

    Thread Starter
    New Member
    Join Date
    Apr 2021
    Posts
    5

    Resolved [RESOLVED] Using arrays to add information to radio buttons/checkboxes on a form

    I'm studying how to use Visual Basic in Visual Studio 2019 and have started learning about arrays using Windows Forms App (.NET Framework). I understand how they work, but am having issues wrapping my head around populating controls with them - specifically, radio buttons and checkboxes. So far, I've only found information on how to programmatically add radio buttons in code, but that's not what I need to do here. In the program I'm creating, I've been asked to create a set of radio buttons inside a groupbox on the form, and then use an array to assign information to those radio buttons.

    The information I need to add is a list of cities: London, Cardiff, Edinburgh, Dublin, Belfast, Oxford.

    Name:  Help!.jpg
Views: 894
Size:  18.6 KB

    How would this work in code? I assume that I'll need to declare the array and assign the city names to each index, then use a for loop to step through the array, but I can't visualise how I would connect the radio buttons to the groupbox...

    I would appreciate any help!

    **Edit 5pm**
    Through a bit of trial and error, I've figured out how to add information to the radio buttons, but it seems to be accessing only one index in the array now.... Could anyone take a look at the code and give me a hint as to what I might have missed?

    Name:  code.jpg
Views: 1128
Size:  19.8 KB

    Name:  help2.jpg
Views: 885
Size:  22.6 KB

    Much appreciated!

    Moderator's Edit
    I've converted the screenshot of code to actual text using the code BB tags. If you would like more information, please visit this thread: https://www.vbforums.com/showthread....rums-Code-Tags
    Code:
    Public Class frmHolidayOptions
        Dim Destinationoptions(3) As String
        Dim Radio_Button() As RadioButton = {RadioButton1, RadioButton2, RadioButton3, RadioButton4}
    
        Private Sub frmHolidayOptions_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Destinationoptions(0) = "London"
            Destinationoptions(1) = "Cardiff"
            Destinationoptions(2) = "Edinburgh"
            Destinationoptions(3) = "Dublin"
    
            For Each Radio_Button As RadioButton In grpDestination.Controls
                For i As Integer = 0 To 3
                    Radio_Button.Text = (Destinationoptions(i))
                Next
            Next
    Last edited by dday9; Apr 5th, 2021 at 07:16 PM.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,302

    Re: Using arrays to add information to radio buttons/checkboxes on a form

    Don't try to think in code. Think in logic and then write code to implement that logic. How would you do it manually? If I gave you a piece of paper with a list of city names on it, what would you to? One of the specific features of VB is that the code reads much like an English sentence so, if you write the appropriate sentence, you have your pseudo-code right off the bat. Once you have the list of cities, for each city on that list you would create a radio button, populate it with the current city name and then add it in the appropriate location. That's virtually VB code already. You may need to do a bit of a mathematical calculation to work out the appropriate location for each control (unless you're allowed to use a TableLayoutPanel or FlowLayoutPanel) but, again, think in logic first, turn that into basic algebra and then write code to implement it. Writing the code should be the last step and you should already know exactly what the code has to do before writing it.

  3. #3
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,989

    Re: Using arrays to add information to radio buttons/checkboxes on a form

    Is this homework? I ask because the requirements are kind of nuts. If it's homework, you HAVE to do it the way you are asked to do it, but if it isn't homework, then there are far better approaches than that.

    If it IS homework, then you might want to post the exact requirements. I can understand why you'd be having a hard time with this one, because those requirements are so awkward that I'm having a hard time with it, also. It's so far from what I'd want to do in this case that I'd want to understand the problem better.

    I can understand creating an array of radiobuttons...sort of, though I still wouldn't do even that. I guess if you had an array of cities, and an array of radiobuttons, then index 0 in one array could be index 0 in the other array...but it's just such a bad way to do it that my mind threatens to walk out just for thinking about it.
    My usual boring signature: Nothing

  4. #4

    Thread Starter
    New Member
    Join Date
    Apr 2021
    Posts
    5

    Re: Using arrays to add information to radio buttons/checkboxes on a form

    Hi Shaggy Hiker, it is homework unfortunately. Even worse, the provider I'm doing it with seems to be very research-focused (which I didn't know beforehand) - so the onus is on me to find any answers... So, the program is a holiday planner, made with a combination of comboboxes, radio buttons and checkboxes. I've written below the section about the radio buttons and checkboxes:

    A holiday company is providing unique holiday tours across the UK. They have asked you to create a program to book and pay for these holidays with them.
    Customers must select one and only one for each of the following options:
    - Destinations (London, Cardiff, Edinburgh, Dublin, Belfast, Oxford).
    - Duration (2 nights, 4 nights, 7 nights).
    You should design your form layout using radio buttons for these options.
    Create arrays to store the destination options, duration options and their prices. Use a for loop to loop over the arrays and add the items to the radio buttons.

    Customers may optionally choose one or more of the following options for their tour:
    - Options (Breakfast, Lunch, Dinner).
    You should design your form layout using checkboxes for these options.
    Create arrays to store the options and their prices. Use a for loop to loop over the arrays and add the items to the checkboxes.


    I hope this helps. My mind has already threatened to walk several times haha.

  5. #5
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,466

    Re: Using arrays to add information to radio buttons/checkboxes on a form

    To create an array of RadioButtons, that would be parallel to your city names array...

    Code:
    Dim RadioButtons() As RadioButton = {RadioButton1, RadioButton2, RadioButton3, RadioButton4, RadioButton5, RadioButton6}
    Then you can loop (not for each) through the cityNames array -
    Code:
    RadioButtons(index).Text = cityNames(index)
    That's the easy way to reference multiple controls and assign them all different values

  6. #6
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,046

    Re: Using arrays to add information to radio buttons/checkboxes on a form

    Quote Originally Posted by Reichan View Post
    I'm studying how to use Visual Basic in Visual Studio 2019 and have started learning about arrays using Windows Forms App (.NET Framework). I understand how they work, but am having issues wrapping my head around populating controls with them - specifically, radio buttons and checkboxes. So far, I've only found information on how to programmatically add radio buttons in code, but that's not what I need to do here. In the program I'm creating, I've been asked to create a set of radio buttons inside a groupbox on the form, and then use an array to assign information to those radio buttons.

    Much appreciated!
    not sure what you mean, do you have to create the controls dynamic?
    this would add a GroupBox to a form

    Code:
     Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            Dim groupBox1 As New GroupBox()
            'Size of GroupBox set here
            groupBox1.SetBounds(50, 50, 200, 150)
            groupBox1.Text = "Select City"
            'add the Groupbox
            Me.Controls.Add(groupBox1)
        End Sub
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  7. #7
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,715

    Re: Using arrays to add information to radio buttons/checkboxes on a form

    I want to take the opportunity to address some issues from your updated code.

    The first issue is that you declare a variable named Radio_Button that is scoped at the form level and then another variable with the same name scoped in the For/Each. This could cause unexpected issues. Take for example you're declaring the form level variable but then looping over grpDestination.Controls, this means that the form level variable is never actually referenced (which is why the variable declaration is light gray in your screenshot).

    The second issue is that you have declared an unnecessary nested loop. You looping over each control in grpDestination.Controls and inside of that you're looping over every item in Destinationoptions. So what actually happens is that each control's text gets set to London, then it is overwritten and the text gets set to Cardiff, then it is overwritten again and the text gets set to Edinburgh, and finally it gets overwritten again and the text gets set to Dublin (which is what you wind up with in your screenshot).

    Another point is not really an issue, but more of an observation. You declare the Radio_Button variable and initialize it with controls, but you declare the Destinationoptions variable and wait to set the values until the Load event. Why not just initialize the variable to begin with:
    Code:
    Dim Destinationoptions() As String = {"London", "Cardiff", "Edinburgh", "Dublin", "Belfast", "Oxford"}
    Something else that you should know, but is probably a little bit more advanced than what you're learning is that there are different ways to declare variables. In my opinion, since you're declaring the destinations that will only be used in frmHolidayOptions and you won't be changing the items in the collection, then I would declare the variable as Private and ReadOnly (I also changed the naming convention to match a more traditional convention):
    Code:
    Private ReadOnly _destinationOptions() As String = {"London", "Cardiff", "Edinburgh", "Dublin", "Belfast", "Oxford"}
    In terms of actually solving your issue, .paul.'s example in post 5 is what I would suggest. However, I would add that when you loop over the collection, you should check if the currently iterated index is less than the collection you're accessing to prevent an IndexOutOfRangeException:
    Code:
    Public Class frmHolidayOptions
        Private ReadOnly _destinationOptions() As String = {"London", "Cardiff", "Edinburgh", "Dublin", "Belfast", "Oxford"}
        Private ReadOnly _radioButtons() As RadioButton = {RadioButton1, RadioButton2, RadioButton3, RadioButton4, RadioButton5, RadioButton6}
    
        Private Sub frmHolidayOptions_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            For index = 0 To _radioButtons.Length - 1
                If (index < _destinationOptions.Length - 1) Then
                    _radioButtons(index).Text = _destinationOptions(index)
                End If
            Next
        End Sub
    End Class
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  8. #8
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,466

    Re: Using arrays to add information to radio buttons/checkboxes on a form

    Quote Originally Posted by dday9 View Post
    Code:
    Public Class frmHolidayOptions
        Private ReadOnly _destinationOptions() As String = {"London", "Cardiff", "Edinburgh", "Dublin", "Belfast", "Oxford"}
        Private ReadOnly _radioButtons() As RadioButton = {RadioButton1, RadioButton2, RadioButton3, RadioButton4, RadioButton5, RadioButton6}
    
        Private Sub frmHolidayOptions_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            For index = 0 To _radioButtons.Length - 1
                If (index < _destinationOptions.Length - 1) Then
                    _radioButtons(index).Text = _destinationOptions(index)
                End If
            Next
        End Sub
    End Class

    You mean...

    Code:
    If (index <= _destinationOptions.Length - 1) Then
    ???

  9. #9
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,715

    Re: Using arrays to add information to radio buttons/checkboxes on a form

    Ahh! That’s what I get for I freetyping it.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  10. #10
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,466

    Re: Using arrays to add information to radio buttons/checkboxes on a form


  11. #11
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,466

    Re: Using arrays to add information to radio buttons/checkboxes on a form

    Quote Originally Posted by dday9 View Post
    Ahh! That’s what I get for I freetyping it.
    Also, declaring and initializing radiobuttons at form scope wouldn't work...

  12. #12

    Thread Starter
    New Member
    Join Date
    Apr 2021
    Posts
    5

    Re: Using arrays to add information to radio buttons/checkboxes on a form

    Hello, sorry for the late reply! @.paul. and @dday9, I changed the code as you recommended and it worked like a charm! Thank you so much!

    I was tying myself up in knots thinking I would need to refer to the specific groupbox the radio buttons were in. It looks like this will also work perfectly with the checkboxes I need to use. Thank you as well for the detailed explanation - that really helped in understanding where I was going wrong.

    As a quick side question that's related, if I had two separate groups of radio buttons (say, one for cities and one for duration), would I simply declare a different set of radio buttons - like so:

    Code:
    Dim Radio_Button() As RadioButton = {RadioButton1, RadioButton2, RadioButton3, RadioButton4, RadioButton5, RadioButton6}
    Dim Radio_Button2() As RadioButton = {RadioButton7, RadioButton8, RadioButton9}
    Last edited by Reichan; Apr 6th, 2021 at 04:47 AM.

  13. #13
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,466

    Re: Using arrays to add information to radio buttons/checkboxes on a form

    Yes. Keep it simple, using one array for each separate group of controls

  14. #14

    Thread Starter
    New Member
    Join Date
    Apr 2021
    Posts
    5

    Re: Using arrays to add information to radio buttons/checkboxes on a form

    That's great; thank you so much!

  15. #15
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,302

    Re: Using arrays to add information to radio buttons/checkboxes on a form

    Quote Originally Posted by Reichan View Post
    Hello, sorry for the late reply! @.paul. and @dday9, I changed the code as you recommended and it worked like a charm! Thank you so much!

    I was tying myself up in knots thinking I would need to refer to the specific groupbox the radio buttons were in. It looks like this will also work perfectly with the checkboxes I need to use. Thank you as well for the detailed explanation - that really helped in understanding where I was going wrong.

    As a quick side question that's related, if I had two separate groups of radio buttons (say, one for cities and one for duration), would I simply declare a different set of radio buttons - like so:

    Code:
    Dim Radio_Button() As RadioButton = {RadioButton1, RadioButton2, RadioButton3, RadioButton4, RadioButton5, RadioButton6}
    Dim Radio_Button2() As RadioButton = {RadioButton7, RadioButton8, RadioButton9}
    Given that RadioButtons operate as a group in the same container, you can just get all the RadioButtons in that container, e.g.
    vb.net Code:
    1. Dim dayRadioButtons = dayGroupBox.Controls.OfType(Of RadioButton)().ToArray()
    You can do the same with other types of controls if you want all and only the controls of that type directly in that container.

  16. #16

    Thread Starter
    New Member
    Join Date
    Apr 2021
    Posts
    5

    Re: Using arrays to add information to radio buttons/checkboxes on a form

    Hi @jmcilhinney,

    Thanks - that does make things a bit clearer for me as well. It's good to know that I have two different ways to trying things out.

  17. #17
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,466

    Re: [RESOLVED] Using arrays to add information to radio buttons/checkboxes on a form

    What jmcilhinney told you, might not return the controls in the order you want them to be...

  18. #18
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,302

    Re: [RESOLVED] Using arrays to add information to radio buttons/checkboxes on a form

    Quote Originally Posted by .paul. View Post
    What jmcilhinney told you, might not return the controls in the order you want them to be...
    That is true. The result will be based on the z-order of the controls. That's basically the order they would be layered over each other if they overlapped. by default, that follows the order you add then to the form/container, i.e. the later they were added, the further to the front of the z-order they will be. You can view and manipulate the z-order of controls using the Document Outline window in the WinForms designer. If you're adding the controls in code then you need to add them in the order you want to get them back, which I would assume that you would do anyway. Set the z-order appropriately and the code I provided will produce the correct order.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width