Creating control arrays in C#

JohnCTX 636 Reputation points
2021-01-16T03:46:58.737+00:00

I am trying to migrate myself to C#.

I am having too many issues while trying to create control arrays in C#.

Users may be able to solve this runtime error in the source code below.

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Control_Duplicator
{
    public partial class ControlDuplicatorForm : Form
    {


        private ComboBox[] myComboBox;


        public ControlDuplicatorForm()
        {
            InitializeComponent();
        }

        private void Create_Determiner_Button_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < myComboBox.Length; i++)
                myComboBox[i].Text = "Combo Row Created";
            //This generates a runtime error.  
        }

    }
}

Regards,

JohnCTX

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,827 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,235 questions
{count} votes

Accepted answer
  1. Alberto Poblacion 1,556 Reputation points
    2021-01-16T10:05:59.4+00:00

    You are missing the "new" on each element of your array. You can't assign the .Text until the instance is created. And also, the array initialization is missing from the code you posted.

    private ComboBox[] myComboBox = new ComboBox[10];
    
    ...
    
             private void Create_Determiner_Button_Click(object sender, EventArgs e)
    
             {
    
                 for (int i = 0; i < myComboBox.Length; i++)
    
                 {
    
                      myComboBox[i] = new ComboBox();
    
                      myComboBox[i].Text = "New Combo Created";
    
                      // If you want to add it to the form:
    
                      myComboBox[i].Left = 20;
    
                      myComboBox[i].Top = 20*i;
    
                      this.Controls.Add(myComboBox[i]);
    
                 }
    
             }
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,036 Reputation points
    2021-01-16T11:51:42.427+00:00

    I realize you have an answer but thought it prudent to indicate there is a cleaner way. If interested the following creates buttons and by using the same logic can create any type of control like a ComboBox, TextBox etc.

    Full source

    https://github.com/karenpayneoregon/forum-questions/tree/master/CreateDynamicControls

    Class

    using System;  
    using System.Collections.Generic;  
    using System.Drawing;  
    using System.Windows.Forms;  
      
    namespace CreateDynamicControls.Classes  
    {  
        public class Operations  
        {  
            public static List<Button> ButtonsList { get; set; }  
            public static int Base { get; set; }  
            public static int Left { get; set; }  
            public static int BaseWidth { get; set; }  
            public static int BaseHeightPadding { get; set; }  
            public static string BaseName { get; set; } = "Button";  
            public static EventHandler EventHandler { get; set; }  
            public static Control ParentControl { get; set; }  
            public static int Index = 1;  
      
            /// <summary>  
            /// Initialize global properties  
            /// </summary>  
            /// <param name="pControl">Control to place button</param>  
            /// <param name="pBase"></param>  
            /// <param name="pBaseHeightPadding"></param>  
            /// <param name="pLeft"></param>  
            /// <param name="pWidth"></param>  
            /// <param name="pButtonClick">Click event for button</param>  
            public static void Internalize(Control pControl, int pBase, int pBaseHeightPadding, int pLeft, int pWidth, EventHandler pButtonClick)  
            {  
                  
                ParentControl = pControl;  
                Base = pBase;  
                BaseHeightPadding = pBaseHeightPadding;  
                Left = pLeft;  
                BaseWidth = pWidth;  
                EventHandler = pButtonClick;  
                ButtonsList = new List<Button>();  
                  
            }  
            public static void CreateButton(string text = "")  
            {  
      
                var button = new Button()  
                {  
                    Name = $"{BaseName}{Index}",  
                    Text = text,   
                    Width = BaseWidth,  
                    Location = new Point(Left, Base),  
                    Parent = ParentControl,  
                    Visible = true  
                };  
      
                button.Click += new System.EventHandler(EventHandler);  
                ButtonsList.Add(button);  
      
                ParentControl.Controls.Add(button);  
                Base += BaseHeightPadding;  
                Index += 1;  
            }  
      
        }  
    }  
      
    

    Form code

    using System;  
    using System.Linq;  
    using System.Windows.Forms;  
    using CreateDynamicControls.Classes;  
      
    namespace CreateDynamicControls  
    {  
        public partial class Form1 : Form  
        {  
            public Form1()  
            {  
                InitializeComponent();  
                  
                Operations.Internalize(this,10,30, 100,100, GenericButtonClick);  
                  
            }  
      
            private void CreateButton_Click(object sender, EventArgs e)  
            {  
                  
                Operations.CreateButton(string.IsNullOrWhiteSpace(ButtonTextButton.Text) ? "(empty)" : ButtonTextButton.Text);  
                  
            }  
      
            private void GenericButtonClick(object sender, EventArgs e)  
            {  
                var button = (Button) sender;  
                MessageBox.Show(button.Name);  
            }  
      
            private void ButtonListButton_Click(object sender, EventArgs e)  
            {  
                ButtonsListBox.DataSource = Operations.ButtonsList.Select(button => button.Name).ToList();  
            }  
        }  
    }  
      
    

    57342-createbuttons.png