Creating an array of a particular Form element in C#

Nipuna Dilhara
1 min readMay 21, 2018

--

Following code-segments show how to create an array of radio buttons.
(Suppose rb0, rb1, rb2 are the names of radio buttons)

System.Windows.Forms.RadioButton[] rbArray=new System.Windows.Forms.RadioButton[3];rbArray[0]=rb0;
rbArray[1]=rb1;
rbArray[2]=rb2;

Also, we can create an array as below,

System.Windows.Forms.RadioButton[] rbArray;
rbArray=new System.Windows.RadioButton[3]{rb0,rb1,rb2};

In above code segments, we have used already created radio buttons. Instead of using existing radio buttons, they can be created dynamically.

for(int i=0; i<3; i++) 
{
rbArray[i]=new RadioButton();
rbArray[i].Text=“rb”;
rbArray[i].Location=new System.Drawing.Point(10, i*10);
this.Controls.Add(rbArray[i]);
}

In a case of creating two-dimensional arrays, we have to change the code as follows.

System.Windows.Forms.RadioButton[,] rbArray;
rbArray=new System.Windows.Forms.RadioButton[,] {{rb00,rb01,rb02}, {rb10,rb11,rb12}, {rb20,rb21,rb22}};

We can also create arrays for other form elements such as text boxes, buttons, list boxes, labels, check boxes, combo boxes etc.

System.Windows.Forms.Label[] lblArray;
lblArray=new System.Windows.Forms.Label[3]{lb0, lb1, lb2};

--

--

Nipuna Dilhara
Nipuna Dilhara

No responses yet