-
Array of Runtime Labels
Using C# 2005, I am trying to create labels at run-time using an array. The code below WITHOUT the array does work without run-time errors:
Code:
namespace sud
{
public partial class sud : Form
{
private Label labelTest = new Label();
public sud()
{
InitializeComponent();
}
private void sud_Load(object sender, EventArgs e)
{
this.labelTest.Size = new System.Drawing.Size(50, 50);
this.labelTest.Location = new System.Drawing.Point(40, 40);
this.labelTest.Name = "cellTest";
this.labelTest.Text = "Test";
this.Controls.Add(labelTest);
}
} // end partial class: sud
} // end namespace: sud
I get this error ONLY at run-time: object reference not set to an instance of an object if I use the code below which uses an ARRAY to create the labels.
Code:
namespace sud
{
public partial class sud : Form
{
private Label[] labelTest2;
public sud()
{
InitializeComponent();
}
private void sud_Load(object sender, EventArgs e)
{
this.labelTest2 = new Label[10];
this.labelTest2[0].Size = new System.Drawing.Size(50, 50);
this.labelTest2[0].Location = new System.Drawing.Point(40, 40);
this.labelTest2[0].Name = "cellTest";
this.labelTest2[0].Text = "Test";
this.Controls.Add(labelTest2[0]);
}
} // end partial class: sud
} // end namespace: sud
Suggestions?
-
Add labelTest2[0] = new Label();
before you call its properties.
You've created an array of 10 Labels, not 10 Labels.
-
I still got the same error but I did manage to get it to work from that suggestion. Changes in blue:
Code:
namespace sud
{
public partial class sud : Form
{
private Label[] labelTest2;
public sud()
{
InitializeComponent();
labelTest2 = new Label[10];
}
private void sud_Load(object sender, EventArgs e)
{
this.labelTest2[0] = new Label();
this.labelTest2[0].Size = new System.Drawing.Size(50, 50);
this.labelTest2[0].Location = new System.Drawing.Point(40, 40);
this.labelTest2[0].Name = "cellTest";
this.labelTest2[0].Text = "Test";
this.Controls.Add(labelTest2[0]);
}
} // end partial class: sud
} // end namespace: sud
Thanks for your help!
-
Yup.
You had 10 references to a label.
It's analgous to in C++ creating 10 pointers to something and trying to access an element of it. It's not going to fly unless you allocate memory to it.