Need an example to show how to display a list of elemets with radio button

Hi Expert,

I need an example to displays a list of elements with dynamic growth radio button

For example, let's assume I have N pet stores, and each store has a number-X pets (e.g. Dog, Birds, Cats, etcs.

I need the form displays these information as follow:

Pet store 1 -
    Dog  (radio button1 )
    Cat   (radio button2)
    Bird  (radio button3 )
Pet store 2 -
   Snake (radio Button4)
   cat (radio Button5)
...
Pet store N -
   Snake (radio Button6)
   cat (radio Button7)
   Rabbit (radio Button8)
...

Also, the radio button should only affect to the corresponding pet store.
In the above example, I should be able to select radio 1, radio 4, and radio 6, but I cannot select both radio 1 and radio2 button.

How can I display this information dynamically in the form?

Thanks so much!  This will be great help

4eyesgirlAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

4eyesgirlAuthor Commented:
Basically, I need to display like the following

Group Box (Pet Store 1)
  radio 1
  radio 2
  radio 3

Group Box (Pet Store 2)
 radio 4
 radio 5
 radio6
...

Need to make sure it growth automatically in the form and resize itself to the appropriate size.


Thanks a millions
4eyes
Fernando SotoRetiredCommented:
Hi 4eyesgirl;

Here is a sample project that does what you want. It uses Panels and not Group Box but that should be no big deal to make them group boxes if that is what you want.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace PetStores
{
      /// <summary>
      /// Summary description for Form1.
      /// </summary>
      public class Form1 : System.Windows.Forms.Form
      {
            private System.Windows.Forms.TextBox PetStoreName;
            private System.Windows.Forms.Label label1;
            private System.Windows.Forms.Button btnCreate;
            private System.Windows.Forms.Panel StorePanel;
            private System.Windows.Forms.ListBox ListAnimals;
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.Container components = null;

            public Form1()
            {
                  //
                  // Required for Windows Form Designer support
                  //
                  InitializeComponent();

                  //
                  // TODO: Add any constructor code after InitializeComponent call
                  //
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if (components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }

            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                  this.PetStoreName = new System.Windows.Forms.TextBox();
                  this.label1 = new System.Windows.Forms.Label();
                  this.ListAnimals = new System.Windows.Forms.ListBox();
                  this.StorePanel = new System.Windows.Forms.Panel();
                  this.btnCreate = new System.Windows.Forms.Button();
                  this.SuspendLayout();
                  //
                  // PetStoreName
                  //
                  this.PetStoreName.Location = new System.Drawing.Point(16, 32);
                  this.PetStoreName.Name = "PetStoreName";
                  this.PetStoreName.TabIndex = 0;
                  this.PetStoreName.Text = "";
                  //
                  // label1
                  //
                  this.label1.Location = new System.Drawing.Point(16, 8);
                  this.label1.Name = "label1";
                  this.label1.TabIndex = 1;
                  this.label1.Text = "Pet Store Name";
                  this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
                  //
                  // ListAnimals
                  //
                  this.ListAnimals.Items.AddRange(new object[] {
                                                                                           "Dog",
                                                                                           "Cat",
                                                                                           "Bird",
                                                                                           "Snake",
                                                                                           "Fish",
                                                                                           "Rabbit"});
                  this.ListAnimals.Location = new System.Drawing.Point(136, 32);
                  this.ListAnimals.Name = "ListAnimals";
                  this.ListAnimals.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
                  this.ListAnimals.Size = new System.Drawing.Size(120, 95);
                  this.ListAnimals.TabIndex = 2;
                  //
                  // StorePanel
                  //
                  this.StorePanel.AutoScroll = true;
                  this.StorePanel.Location = new System.Drawing.Point(16, 144);
                  this.StorePanel.Name = "StorePanel";
                  this.StorePanel.Size = new System.Drawing.Size(336, 168);
                  this.StorePanel.TabIndex = 3;
                  //
                  // btnCreate
                  //
                  this.btnCreate.Location = new System.Drawing.Point(280, 32);
                  this.btnCreate.Name = "btnCreate";
                  this.btnCreate.TabIndex = 4;
                  this.btnCreate.Text = "Create";
                  this.btnCreate.Click += new System.EventHandler(this.btnCreate_Click);
                  //
                  // Form1
                  //
                  this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                  this.ClientSize = new System.Drawing.Size(376, 330);
                  this.Controls.Add(this.btnCreate);
                  this.Controls.Add(this.StorePanel);
                  this.Controls.Add(this.ListAnimals);
                  this.Controls.Add(this.label1);
                  this.Controls.Add(this.PetStoreName);
                  this.Name = "Form1";
                  this.Text = "Form1";
                  this.ResumeLayout(false);

            }
            #endregion

            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                  Application.Run(new Form1());
            }

            private int y = 0;
            private int x = 0;

            private void btnCreate_Click(object sender, System.EventArgs e)
            {
                  if (PetStoreName.Text == "" || ListAnimals.SelectedItems.Count <= 0)
                         return;
                  
                  int x_animal = 0;
                  Panel p = new Panel();
                  p.Name = "Panel" + PetStoreName.Text;
                  p.Parent = StorePanel;
                  p.Location = new Point(x, y);
                  p.Size = new Size(StorePanel.Width - 2, 26);
                  foreach (string animal in ListAnimals.SelectedItems)
                  {
                        RadioButton rb = new RadioButton();
                        rb.Name = "rb" + animal;
                        rb.Location = new Point(x_animal, 0);
                        rb.Size = new Size(55, 24);
                        rb.Text = animal;
                        rb.Parent = p;
                        rb.CheckedChanged += new System.EventHandler(this.rb_CheckedChanged);
                        x_animal += 56;
                  }
                  p.Show();
                  y += 40;
            }

            private void rb_CheckedChanged(object sender, System.EventArgs e)
            {
                  RadioButton rb = (RadioButton) sender;
                  Console.WriteLine("Store Panel = " + rb.Parent.Name + "Animal was " +
                        rb.Name + " Was Checked");
            }

      }
}


Fernando

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
gbzhhuCommented:
Since I spent quite some time building a solution for you, I will provide it below despite Fernandos solution so you have a choice to make as to what solution best does what you are after

//====================================
//The PetStore class which basically represent the store
//====================================

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;

namespace Store
{
    public enum PetType
    {
        Cat,
        Dog,
        Bird,
        Snake,
        Rabbit
    }

 
    class PetStore
    {
        private ArrayList pets = new ArrayList();

        public ArrayList Pets
        {
            get { return this.pets; }
            set { this.pets = value; }
        }

        private string name;
        public string Name
        {
            get { return this.name; }
            set { this.name = value; }
        }
    }
}

//====================================
//The Pet class which represent the pets
//====================================
using System;
using System.Collections.Generic;
using System.Text;

namespace Store
{
    class Pet
    {
        public Pet(){}

        public Pet(string name, PetType animalType)
        {
            this.name = name;
            this.animalType = animalType;
        }

        private string name;
        public string Name
        {
            get{return this.name; }
            set { this.name = value; }
        }

        private PetType animalType;
        public PetType AnimalType
        {
            get { return this.animalType; }
            set { this.animalType = value; }
        }
    }
}

//====================================
//The form code that does the whole thing
//====================================

First on a form put a Panel, call it pnlStores (so that the code compiles, you can later on rename it).  Set this panel's AutoScroll property to true
Next on the form but a Button, call it btnTest

Now double click on the button so that you get the click event hooked for you.  In the click event add this code

            stores[0] = new PetStore();
            stores[0].Pets.Add(new Pet("Saba", PetType.Cat));
            stores[0].Pets.Add(new Pet("Will", PetType.Dog));
            stores[0].Pets.Add(new Pet("MOnty", PetType.Snake));
            stores[0].Pets.Add(new Pet("Birdy", PetType.Bird));
            stores[0].Pets.Add(new Pet("Matty", PetType.Rabbit));

            stores[1] = new PetStore();
            stores[1].Pets.Add(new Pet("Slimy", PetType.Snake));
            stores[1].Pets.Add(new Pet("FlayAway", PetType.Bird));

            stores[2] = new PetStore();
            stores[2].Pets.Add(new Pet("Buster", PetType.Cat));
            stores[2].Pets.Add(new Pet("Chloe", PetType.Dog));
            stores[2].Pets.Add(new Pet("Aussie", PetType.Bird));
            stores[2].Pets.Add(new Pet("Teethy", PetType.Rabbit));

            this.DisplayOptions();


Last but not least add this code to the form that performs the major task of creating the controls

        private void DisplayOptions()
        {
            GroupBox prevGB = null;

            foreach (PetStore store in this.stores)
            {
                RadioButton prevRB = null;

                GroupBox gb = new GroupBox();
                gb.Name = store.Name;
                gb.Text = store.Name;
                this.pnlStores.Controls.Add(gb);

                gb.Left = 5;
                gb.Width = this.pnlStores.Width - 20;

                if (prevGB == null)
                {
                    gb.Top = 10;
                }
                else
                {
                    gb.Top = prevGB.Top + prevGB.Height + 10;
                }

                gb.Height = (store.Pets.Count * 25) + (store.Pets.Count * 10);

                prevGB = gb;

                foreach (Pet pet in store.Pets)
                {
                    RadioButton rb = new RadioButton();
                    rb.Name = pet.Name;
                    rb.Text = pet.Name;
                    gb.Controls.Add(rb);

                    rb.Left = 5;
                    rb.Width = gb.Width - 20;

                    if (prevRB == null)
                    {
                        rb.Top = 10;
                    }
                    else
                    {
                        rb.Top = prevRB.Top + prevRB.Height + 10;
                    }

                    prevRB = rb;
                }
            }
        }  


Hope that helps

Cheers
Hassan
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

gbzhhuCommented:
Just realised I forgot to include the array of PetStores declaration

In the form code and outside from any method add this

        PetStore[] stores = new PetStore[3];

You can put this just above the BtnTest_Click event

This is an example of a fixed number of pets.  If you want dynamic number of pets it is easy to modify.  Need help with that then let me know

vo1dCommented:
one comment to gbzhhu PetStore class.
i would recommend to make a collection for your pet class instead of using an arraylist.
arraylists have a disadvantage because all added objects are boxed to type object and unboxed to their nature type on indexing.

4eyesgirlAuthor Commented:
Thanks guys,

I tried out both answer and both works great.

So I split the point and since Fernado provides the solution first, I reward him 300 points.

Thanks so much
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.