Can we dynamically reference an element (server side)

Let's say that I have elements with the identifier "Input1", "Input2" and "Input3".

Is there a way to migrate them and then write:

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

in jquery you can just edit an element like $ ('# Input' + i) and pass through i, something like that would be very useful in ASP code.

+6
source share
3 answers

Edit : Spirit, I again searched for all the x controls on the 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. } } 

View ... based on the naming scheme of your example, 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 parent. Control myControl2 = myControl1.Parent; Response.Write("Parent of the text box is : " + myControl2.ID); } else { Response.Write("Control not found"); } } } 

This will allow you to scroll through items with a digital name, but otherwise it is somewhat inconvenient.

+2
source

If you know the parent container, you can loop its .Controls () property. If you start at the page level and work recursively, you can end up with all the controls on the page.

See the answer for more details.

+1
source

I like to keep things strongly typed, so I keep them on a list. This makes the code more refactoring resistant and there is no need to drop it. Listing all your controls in the list takes a little more work, but it often costs me.

I'm not sure what types of controls you have, so I will pretend that they are of type Input .

 var InputControls = new List<Input>(){Input1, Input2, Input3}; foreach(var input in InputControls) { input.Value = 1; } 
0
source

Source: https://habr.com/ru/post/984787/


All Articles