none
how to add many objects into a list? RRS feed

  • Question

  • Hi,

    I have about 60 pictureboxs in the program, named as picturebox1, picturebox2...What I am seeking for is a way to add all them into a list (or other forms of collection if it's a better choice), so I can access each of them by index in a for loop, can anyone please suggest some method to do this? Thank you!


    Lots of appreciation for all the answers!
    • Edited by KDlsw Wednesday, August 15, 2018 4:44 AM
    Tuesday, August 14, 2018 7:00 AM

Answers

  • When you can create them when program is running, you can store them in list immediatelly when you create them. You can change properties by loop list of picture box.

    If you want to add pictureboxes when design form(s) you will need to find all fields which are picturebox type by reflection in form onLoad method.

    private void Form1_Load(object sender, EventArgs e)
            {
                List<PictureBox> pictureBoxes = new List<PictureBox>();
                foreach (System.Reflection.FieldInfo fi in this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic |
                             System.Reflection.BindingFlags.Instance))
                {
                    if (fi.FieldType.Name == "PictureBox")
                    {
                        pictureBoxes.Add(fi.GetValue(this) as PictureBox);
                    }
                }
            }

    • Marked as answer by KDlsw Wednesday, August 15, 2018 4:42 AM
    Tuesday, August 14, 2018 8:48 AM

All replies

  • I suppose you added pictureboxes when design form(s). Could you create it when program is running?
    Tuesday, August 14, 2018 8:12 AM
  • Yes, and yes i think i can, after i created them, how should I change some properties of all 60 of those picturebox dynamically? thank you.
    • Edited by KDlsw Tuesday, August 14, 2018 8:18 AM
    Tuesday, August 14, 2018 8:15 AM
  • When you can create them when program is running, you can store them in list immediatelly when you create them. You can change properties by loop list of picture box.

    If you want to add pictureboxes when design form(s) you will need to find all fields which are picturebox type by reflection in form onLoad method.

    private void Form1_Load(object sender, EventArgs e)
            {
                List<PictureBox> pictureBoxes = new List<PictureBox>();
                foreach (System.Reflection.FieldInfo fi in this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic |
                             System.Reflection.BindingFlags.Instance))
                {
                    if (fi.FieldType.Name == "PictureBox")
                    {
                        pictureBoxes.Add(fi.GetValue(this) as PictureBox);
                    }
                }
            }

    • Marked as answer by KDlsw Wednesday, August 15, 2018 4:42 AM
    Tuesday, August 14, 2018 8:48 AM
  • Hi KDIsw,

    You can create an array of picture box and access them by the array index from your code. You have to change the below code as per your requirement Hope this will help you.

    PictureBox[] picturebox = new PictureBox[1000]; picturebox[pbIndex].Name = ""; picturebox[pbIndex].Location = new Point(pbXaxis, pbYaxis); picturebox[pbIndex].Size = new Size("", "");

    Form1.Controls.Add(picturebox[pbIndex]);  



    Thanks,
    Sabah Shariq

    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered "Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]

    Tuesday, August 14, 2018 11:00 AM
    Moderator
  • Perhaps a Dictionary<int,PictureBox), this would be a private variable. Create it in form Shown event as shown below. Later use it. In this case I have 6 PictureBox controls.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Xml.Linq;
    using WindowsFormsApp1.Properties;
    
    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            private Dictionary<int,PictureBox> dictPictureBoxes;
            public Form1()
            {
                InitializeComponent();
                Shown += Form1_Shown;
            }
    
            private void Form1_Shown(object sender, EventArgs e)
            {
                dictPictureBoxes = this.Descendants<PictureBox>()
                    .Select((c, i) => new { Index = i + 1, PictureBox = c }).ToArray().ToDictionary(x => x.Index, x => x.PictureBox);
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                foreach (KeyValuePair<int,PictureBox> item in dictPictureBoxes)
                {
                    Console.WriteLine($"{item.Key} - {item.Value.Location.X}");
                }
    
                int pictureBoxIndex = 4;
                if (dictPictureBoxes.ContainsKey(pictureBoxIndex))
                {
                    dictPictureBoxes[pictureBoxIndex].Image = Resources.Apple1;
                }
    
            }
        }
        
        /// <summary>
        /// Place this class in it's own file
        /// </summary>
        public static class Extensions
        {
            public static IEnumerable<T> Descendants<T>(this Control control) where T : class
            {
                foreach (Control child in control.Controls)
                {
    
                    T childOfT = child as T;
                    if (childOfT != null)
                    {
                        yield return (T) childOfT;
                    }
    
                    if (!child.HasChildren) continue;
                    foreach (T descendant in Descendants<T>(child))
                    {
                        yield return descendant;
                    }
                }
            }
        }
    }
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, August 14, 2018 12:10 PM
    Moderator