Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we dynamically reference element (Server Side)

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.

like image 901
colobusgem Avatar asked Apr 07 '15 12:04

colobusgem


2 Answers

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.

like image 92
Pseudonym Avatar answered Oct 12 '22 21:10

Pseudonym


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.

like image 20
Bradley Uffner Avatar answered Oct 12 '22 19:10

Bradley Uffner