question

JohnCTX-6479 avatar image
0 Votes"
JohnCTX-6479 asked ·

Creating control arrays in C#

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


dotnet-csharpwindows-forms
· 1
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I have changed the entire code in C# just to make it better.
Expect that it would have no compiling or runtime errors.

57236-screenshot-34.png



Regards,

JohnCTX

0 Votes 0 ·
screenshot-34.png (123.3 KiB)
APoblacion avatar image
1 Vote"
APoblacion answered ·

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]);

              }

          }

· Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered ·

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



createbuttons.png (8.1 KiB)
· 1 · Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks. I'll try your code snippet.
I don't know if they are any guarantees; it is worth a shot.

Regards,

JohnCTX

0 Votes 0 ·