views:

388

answers:

7

Hello,

Imagine we have 5 string variables and we want to assign "Foo" to them during runtime.

Instead of this

string a1 = "Foo";
string a2 = "Foo";
string a3 = "Foo";
string a4 = "Foo";
string a5 = "Foo";

Can't we use something like this:

for(int i = 0;i < 5;i++)
{
    a+i = "Foo";
}

Is it impossible to access them in a similiar way?

+2  A: 

You can access controls by name, but it would be a lot cleaner to add an array of label items to your page then access the array using the integer.

Steve Haigh
+1  A: 

You can create an array or array list of labels, and put your label into them. Then you can do something similar to this.

J.W.
Could you provide an example,Its not about labels,but variables(int a1,a2,a3,a4,a5,a6...)?
John
+2  A: 

You can by iterating through the label's parent's controls:

for (int i=0; i<= parent.controls.count(); i++)
{
    if (parent.controls("label" + i)  != null)
    {
         ...
    }
}

HTH

EDIT:

After your edit, the only way I could see of doing it would be to add them to a list/array/dictionary and iterate through that, although the principle is the same.

Pondidum
I edited my question,labels were just an example.The problem are variables.How to do this with variables(a1,a2,a3,a4,a5,a6,a7....)?
John
+4  A: 
Label[] labels = new Label[] { label1, label2, label3, label4, label5 };

for (int i = 0; i < labels.Length; i++)
{
    labels[i].Text = "Foo";
}
LukeH
+1  A: 

If all of the labels have the same parent, and that parent has no other label controls contained within you could do the following:

foreach (Control lbl in ParentControl)
{
    if (lbl is TextBox)
    {
        ((Label)lbl).Text = "Foo";
    }
}
Richard Slater
+4  A: 

As others have said, an array (or another collection) is a much better way of doing this.

Think of an array as just being a collection of variables which you always access by index.

I can't think of any reason why you'd want to have a set of variables as shown in your question. If you absolutely have to do that, and they're instance/static variables, you could use reflection to access them if you really wanted to - but using an array or other collection would be much, much better.

Jon Skeet
Thanks Jon! I will buy your book again if you provide an example.I tried to put them in a <List> ,but I'm new to Generics :)
John
I solved it,thanks!
John
+1  A: 

Assuming we're talking about webforms here, there's a FindControl() method you can use.

private void Button1_Click(object sender, EventArgs MyEventArgs)
{
  // Find control on page.
  TextBox myControl1 = (TextBox) FindControl("Label1");
  if(myControl1!=null)
  {
     string message = myControl1.Text;
  }
}
Ian Jacobs