Reputation: 7170
i've 6 label controls in a form: label1, label2...label6. How to 'refer' to the control in a loop like this:
for (i=1;i<=6;i++) {
label[i].text = ...;
}
Thank you
Upvotes: 0
Views: 94
Reputation: 45083
Let's assume this is WinForms and that your "labels" are controls - the Form
has a Controls
property, which is a collection of controls associated with that container, so, we ought to be able to use Linq to query this, get the controls of the type we want, then iterate them, as such:
using System.Linq;
var labels = from control in Controls where control is Label select control;
for (i = 1; i <= controls.Count; i++)
{
labels[i].text = i.ToString();
}
A little rough, but you aren't very specific - it should be a decent starting point if nothing else.
EDIT:
OK, I thought I'd take the time to look into it, and Form.Controls
doesn't like being used in Linq (in that straightforward way, at least), so as an alternative, this should help:
private List<Label> GetLabels()
{
var result = new List<Label>();
foreach (var control in Controls)
{
if (control is Label)
{
result.Add(control as Label);
}
}
return result;
}
The above method could even be factored in a genericised way rather simply; but then you can proceed:
var labels = GetLabels();
for (int i = 0; i <= labels.Count; i++)
{
labels[i].Text = i.ToString();
}
Upvotes: 1
Reputation: 20620
Here's another way:
for (int n = 1; n < 4; n++)
{
Control[] Temp = Controls.Find("Label" + n, false);
Temp[0].Text = n.ToString();
}
Upvotes: 2
Reputation: 18064
You can implement something like this:-
int y = 0;
int index = 0;
Label[] labels = new Label[6];
foreach (Student std in StudentList)
{
labels[index] = new Label();
labels[index].Text = std.Name;
labels[index].ForeColor = Color.Red;
labels[index].Location = new Point(0, y);
labels[index].Size = new Size(50, 12);
y = y + 10;
++index;
}
// Add the Label control to the form.
mPanel.Controls.AddRange(labels);
Upvotes: 1