Can we dynamically reference element (Server Side)
Asked Answered
S

3

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.

Separatist answered 7/4, 2015 at 12:46 Comment(2)
you probably need to use the Control.FindControl methodObscenity
it's about webforms?Untinged
J
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.

Jude answered 7/4, 2015 at 12:53 Comment(2)
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?Separatist
depending on your input type you may have to cast it like so: ((TextBox)myControl1).ValueJude
S
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.

Suburbanize answered 7/4, 2015 at 12:52 Comment(0)
W
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;
}
Weintraub answered 7/4, 2015 at 13:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.