6

Say I have the elements with the ID's of "Input1", "Input2" and "Input3".

Is there a way to loop through them rather then having to write:

Input1.Value = 1;
Input2.Value = 1;
Input3.Value = 1;

in jquery you can just refrence an element like $('#Input'+i) and loop through i, something similar would be very useful in ASP code behind.

yogi970
  • 446
  • 5
  • 14
colobusgem
  • 473
  • 1
  • 4
  • 18

3 Answers3

2

Edit: Duh, I searched again for finding all "x" controls on page and came up with the following source code:

foreach(Control c in Page.Controls)
{
    if (c is TextBox)
    {
        // Do whatever you want to do with your textbox.
    }
}

Kind of ... based on your example naming scheme you can do something like the following:

    private void Button1_Click(object sender, EventArgs MyEventArgs)
    {
          string controlName = TextBox

          for(int i=1;i<4;i++)
          {
           // Find control on page.
           Control myControl1 = FindControl(controlName+i);
           if(myControl1!=null)
           {
              // Get control's parent.
              Control myControl2 = myControl1.Parent;
              Response.Write("Parent of the text box is : " +  myControl2.ID);
          }
          else
          {
             Response.Write("Control not found");
          }
         }

    }

This will let you loop through numerically named controls but otherwise it is somewhat clunky.

Pseudonym
  • 2,052
  • 2
  • 17
  • 38
  • Ok i tried that, but the Control Object doesn't have Value. How do I cast it or tell the code that this control *should* be an input type and therefore has a Value definition? – colobusgem Apr 07 '15 at 13:08
  • depending on your input type you *may* have to cast it like so: ((TextBox)myControl1).Value – Pseudonym Apr 07 '15 at 13:11
1

If you know the parent container you can loop though its .Controls() property. If you start at the Page level and work recursively, you can eventually reach all controls on the page.

See the answer from this question for more details.

Community
  • 1
  • 1
Bradley Uffner
  • 16,641
  • 3
  • 39
  • 76
0

I like to keep things strongly typed, so I store them in a list. This makes the code more resilient to refactoring and there's no need to cast. It takes a slight bit more upfront work to put all your controls into the list, but to me it's often worth it.

I'm not sure what type your controls are, so I'm going to pretend they're of type Input.

var InputControls = new List<Input>(){Input1, Input2, Input3};
foreach(var input in InputControls)
{
    input.Value = 1;
}
mason
  • 31,774
  • 10
  • 77
  • 121