Work with Controls

  • Thread starter Thread starter Alberto
  • Start date Start date
A

Alberto

I have some labels with this names: lbl1, lbl2, lbl3, ...
It's very unconfortable write something like
lbl1.Text =...
lbl2.Text = ...
....
lbl24.Text = ...

Can it be done in an easy way (something like in the way of Visual Basic
6.0)?

Thanks
 
Alberto,

Assuming they are all labels, you could do something like this (using
Reflection):

// The label.
Label pobjLabel = null;

// The type.
Type pobjThisType = this.GetType();

// Loop through the number of labels, assume there are 10.
for (int pintIndex = 1; pintIndex <= 10; pintIndex++)
{
// Set the label.
pobjLabel = (Label) pobjThisType.GetField("lbl" +
pintIndex.ToString()).GetValue(this);

// Set the text.
pobjLabel.Text = "some text";
}

Hope this helps.
 
Hi Alberto
I have some labels with this names: lbl1, lbl2, lbl3, ...
It's very unconfortable write something like
lbl1.Text =...
lbl2.Text = ...
....
lbl24.Text = ...

Can it be done in an easy way (something like in the way of Visual Basic
6.0)?

Thanks

Nicholas's solution is very interesting... but i can show you the other
way:

// in class add field:

private Label[] labelTab;

// in class constructor... after "InitializeComponent();" line

labelTab=new Label[] { lbl1
, lbl2
, lbl3
...
, lbl24 };

Then you can access those labels through the labelTab's index.

Regards

Marcin
 
Back
Top