dpetek
dpetek

Reputation: 635

Array of Labels

How to create array of labels with Microsoft Visual C# Express Edition ? Is there way to do it with graphical (drag'n'drop) editor or I have to manually add it to auto generated code ?

Upvotes: 5

Views: 53494

Answers (4)

Jose Quispe
Jose Quispe

Reputation: 1

int i=0;
ControlNum=10;
Label[] lblExample= new Label[];
for(i=0;i<ControlNum;i++)
{
  lblExample[i] = new Label();
  lblExample[i].ID="lblName"+i;  //lblName0,lblName1,lblName2....

 Form1.Controls.Add(lblExample[i]);
}

xD ...

Joshit0..

Upvotes: 0

Ali Irawan
Ali Irawan

Reputation: 2134

Label[ , ] _arr = new Label[4 , 4];

private void Form1_Load(object sender, EventArgs e)
{
 for(int i=0;i<4;i++){
    for(int j=0;j<4;j++){
        _arr[i ,j] = new Label();
        _arr[i ,j].Text = ""+i+","+j;
        _arr[i ,j].Size = new Size(50,50);
        _arr[i ,j].Location = new Point(j*50,i*50);
        //you can set other property here like Border or else
        this.Controls.Add(_arr[i ,j]);
    }
 }
}

if you want to set Border of Label in C# maybe you should check http://msdn.microsoft.com/en-us/library/system.windows.forms.label.aspx

Label have property called Border. Please check it. Thanks

Upvotes: 0

nightcoder
nightcoder

Reputation: 13519

You have to manually add it. But don't add it to auto generated code as it can be overwritten by Visual Studio designer.

I would add it in Load event handler for the form. The code can look like this:

Label[] labels = new Label[10];
labels[0] = new Label();
labels[0].Text = "blablabla";
labels[0].Location = new System.Drawing.Point(100, 100);
...
labels[9] = new Label();
...

PS. Your task seems a little unusual to me. What do you want to do? Maybe there are better ways to accomplish your task.

Upvotes: 14

C. Ross
C. Ross

Reputation: 31878

You can add the labels to the form using the GUI editor, then add those to the array in form load.

Label[] _Labels = new Label[3];
private void MyForm_Load(object sender, EventArgs e)
{
    _Labels[0] = this.Label1;
    _Labels[1] = this.Label2;
    _Labels[2] = this.Label3;
}

This will at least make setting the location easier. Also you might want to consider using the FlowLayoutPanel if you're dynamically creating labels (or any control really).

Upvotes: 7

Related Questions