Author: DevASP
Download Source Code : 674_ArrayOfControlsObject.zip
In this article I will try to explain you with the sample program that how you can create the array of objects in C#.
While creating application some time we need to
maintain/create arrays of simple constant variables or we need to maintain
array of objects. C# allows the developer to create array of objects same as
simple array. The only difference is first we create object of array then we
assign value of objects in array.
To begin with application, create a new windows application
in C# and drop the listbox control, button control and checkbox control on
form.
Now in code behind declare two global arrays of controls and
define the following method:
Control[]
arr = new Control[10];
Control[]
arr1 = new Control[10];
public Control[]
arrayOfControl()
{
for
(int i = 0; i < 10; i++)
{
arr[i] = new Control();
}
return
arr;
}
After adding the following code now adds two events (button
click event and Checkbox check change events).
private
void button1_Click(object
sender, EventArgs e)
{
arr1 = arrayOfControl();
for
(int i = 0; i < 10; i++)
{
Button
btn = new Button();
arr[i].Controls.Add(btn);
if
(arr[i].Contains(btn) == true)
{
listBox1.Items.Add("btn added");
}
}
}
This method defines the new button control and adds that
control in array of controls. Similarly we can add the check box control in
array of controls:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
arr1 = arrayOfControl();
for (int i = 0; i < 10; i++)
{
CheckBox
chk = new CheckBox();
arr[i].Controls.Add(chk);
if
(arr[i].Contains(chk) == true &&
checkBox1.Checked == true)
{
listBox1.Items.Add("Checkbox Control Added");
}
else
if(checkBox1.Checked == false)
listBox1.Items.Remove("Checkbox Control Removed");
}
}
In similar fashion we can store controls object in array of
object and use them in our application.