private ArrayList label= new ArrayList(30);
Label label_class = new Label();
Random r = new Random();
for (int i = 0; i < label.Count; i++) {
((Label)label[i]).Location = new Point(r.Next(ClientRectangle.Right -10),
r.Next(ClientRectangle.Bottom - 10));
((Label)label[i]).Text = "o";
((Label)label[i]).Click += new EventHandler(Form1_Load);
this.Controls.Add((Label)label[i]);
((Label)label[i]).Show();
}
This for loop is inside the Form1_Load so that it will run when the form is loading..
the problem is that, when I break point, I see that the code inside the forloop is not noticed by the break point/does not run. why is that?? and how can i create many labels randomly placed on form1(window form)
The issue is in
private ArrayList label= new ArrayList(30);
This creates an ArrayList of size 30, not one with 30 elements.
If you do something like
List<Label> labels = new List<Label>();
for (int i = 0; i < 30; i++) {
var temp = new Label();
temp.Location = new Point(r.Next(ClientRectangle.Right -10),
r.Next(ClientRectangle.Bottom - 10));
temp.Text = "o";
temp.Click += new EventHandler(Form1_Load);
temp.BackColor = System.Drawing.Color.White;
this.Controls.Add(temp);
temp.Show();
labels.Add(temp)
}
It should work.
In addition, notice my use of List<Label> instead of ArrayList there are cases where you will want to have the ability to specify the objects you are taking out but generally ( and in this case ) the generic forms where you specify the type will sure you much better. You will not need to do all of the boxing that you are doing and you will write fewer lines of code all of which will be more readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With