Reputation: 85
I'm trying the following code:
for (int i = 0; i < students.Length; i++)
{
"student" + i.ToString().Text = students[i];
}
I already have many labels which each one has name like: student1 student2 student3 . .
But I got this error: Error 1 'string' does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) F:\Homework\Homework\Form1.cs 161 46 Homework
Any help please??!
Upvotes: 2
Views: 6155
Reputation: 32511
this may help
Controls.Find(string.Format("student{0}", i));
A better solution:
Set the Tag
property of you Labels
as follow:
Student1.Tag = 1;
Student2.Tag = 2;
Student3.Tag = 3;
I assume that your Labels
are in a container control named container
. use this code:
foreach(var item in container.Children) //based on your container type this line may change
{
if(item is Label)
{
Label temp = ((Label)item);
temp.Text = students[int.Parse(temp.Tag.ToString())]
}
}
Upvotes: 3
Reputation: 3920
By doing i.ToString()
you are given a string, which does not have the property Text :). That is what is causing your exception.
If Students
is a list of controls that have the property .Text
then use that and remove the ToString()
else, remove the .Text
.
Upvotes: 0
Reputation: 499392
You can't have dynamic variable names, in just about any language.
Looks like you are looking to have a collection or array of controls.
Something like:
var studentControls = new List<Control>();
studentControls.Add(student1);
studentControls.Add(student2);
...
for (int i = 0; i < students.Length; i++)
{
studentControls[i].Text = students[i];
}
Upvotes: 8