How to create an array of label

  • Thread starter Thread starter jhs
  • Start date Start date
J

jhs

Hello,

I developping a .NET windows form application an need some help to create an
array of System.Windows.Forms.Label in order to be able to manage all of
them using index.
I'm trying to do this in form_load void:
System.Windows.Forms.Label[] labelArray = new
System.Windows.Forms.Label[91];

for (i=1;i<91;i++)

{

labelArray.Size = new System.Drawing.Size(33, 33);

labelArray.Location = new System.Drawing.Point(i, i);

labelArray.Text=i.ToString();

this.Controls.AddRange(new System.Windows.Forms.Control[] {labelArray});


But at running time i get a 'System.NullReferenceException'

How do i have to create my array in order to avoid to create all labels at
design time.

Thanks in advance
 
you have to intialize to new label in each loop, becoz the array values will
be null.

System.Windows.Forms.Label[] labelArray = new
System.Windows.Forms.Label[91];

for (i=1;i<91;i++)
{

//intialize new label
labelArray = new Label();

labelArray.Size = new System.Drawing.Size(33, 33);

labelArray.Location = new System.Drawing.Point(i, i);

labelArray.Text=i.ToString();

this.Controls.AddRange(new System.Windows.Forms.Control[] {labelArray
});
}

Shak
 
You need to add the following to your loop to create a new instance of a
label:
labelArray = new Label();
You may also have an issue with all of the labels being on top of each
other. I'm not sure what you are looking to accomplish. To space them out
more, you could do something like:

labelArray.Location = new System.Drawing.Point(i*30, i*30);
 
* "jhs said:
I developping a .NET windows form application an need some help to create an
array of System.Windows.Forms.Label in order to be able to manage all of
them using index.
I'm trying to do this in form_load void:
System.Windows.Forms.Label[] labelArray = new
System.Windows.Forms.Label[91];

for (i=1;i<91;i++)

{

\\\
labelArray = new Label();
///
labelArray.Size = new System.Drawing.Size(33, 33);

labelArray.Location = new System.Drawing.Point(i, i);

labelArray.Text=i.ToString();

this.Controls.AddRange(new System.Windows.Forms.Control[] {labelArray});


Replace the line above with:

\\\
this.Controls.Add(labelArray);
///
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top