The Way to Programming
The Way to Programming
I’ve been learning some C# and I want to have a grid of labels appear on my screen when I press the button new.
Here’s my code so far:
private void PlaceLabels(int width, int height)
{
int xAs = 50;
int yAs = 20;
Label[,] labels = new Label[width, height];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
labels[x, y] = new Label();
labels[x, y].Size = new System.Drawing.Size(50, 50);
labels[x, y].Location = new System.Drawing.Point(xAs, yAs);
yAs += 10;
}
xAs += 10;
}
}
But when I run it, nothing happens.. Can someone tell me if there is an error in my code I've also tried a jagged array of labels, maybe it'd help, but no:
private void PlaceLabels(int width, int height)
{
int xAs = 50;
int yAs = 20;
Label[][] labels = new Label[width][];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
labels[x] = new Label[height];
labels[x][y] = new Label();
labels[x][y].Size = new System.Drawing.Size(50, 50);
labels[x][y].Location = new System.Drawing.Point(xAs, yAs);
yAs += 10;
}
xAs += 10;
}
}
You aren’t actually adding the labels to the form control collection so they won’t be drawn.
private void PlaceLabels(int width, int height)
{
int xAs = 50;
int yAs = 20;
Label[,] labels = new Label[width, height];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
labels[x, y] = new Label();
labels[x, y].Size = new System.Drawing.Size(50, 50);
labels[x, y].Location = new System.Drawing.Point(xAs, yAs);
this.Controls.Add(labels[x, y]); // here
yAs += 10;
}
xAs += 10;
}
}
Note: If 'this' isn't the context of the form you would need to pass the form instance as a parameter so it knows which form to draw the controls to. Also, you're not adding any label text so the label still won't be visible.
Sign in to your account