Sunday, May 1, 2011

C#: How do i assign many variables with an integer(i) in for loop?

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?

From stackoverflow
  • 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.

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

    John : Could you provide an example,Its not about labels,but variables(int a1,a2,a3,a4,a5,a6...)?
  • 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.

    John : 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....)?
  • Label[] labels = new Label[] { label1, label2, label3, label4, label5 };
    
    for (int i = 0; i < labels.Length; i++)
    {
        labels[i].Text = "Foo";
    }
    
  • 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";
        }
    }
    
  • 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.

    John : Thanks Jon! I will buy your book again if you provide an example.I tried to put them in a ,but I'm new to Generics :)
    John : I solved it,thanks!
  • 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;
      }
    }
    

0 comments:

Post a Comment