Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create labels inside a For loop

Tags:

c#

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)

like image 886
Jeo Talavera Avatar asked Dec 02 '25 16:12

Jeo Talavera


1 Answers

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.

like image 199
zellio Avatar answered Dec 06 '25 00:12

zellio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!