Changing Multiple Label Controls Using a Loop

Consecutive Processing with Multiple Server Controls

In Asp.Net it's pretty easy to change the properties of a server control with code. For example, the text property of a label object;

Label1.Text = "Selam";

can be set as above.

Well, if there are many labels to be changed, for example, if the Text properties of all 100 Label controls are to be changed, what can we do? When we try to change all of them one by one, 100 lines of code will appear.

Instead, this can be done in a loop. We have 100 Label controls and their names are Label1, Label2, ... , Label100. That is, the "Label" parts are common, and the number at the end is assigned sequentially.

First of all, let's say, something like this doesn't work.: Label[ i ]

In Asp.Net pages, the FindControl method is used to find a control by its Id. The Id of the control to be accessed is written in the FindControl method parenthesis. Using this method, let's set up a loop like this:

for (int i = 1; i <= 100; i++)
{
    var label = ((Label)FindControl("Label" + i));
 
    label.Text = i.ToString();
 
}

With the above 3-line code, we have changed the Text properties of 100 labels.

FindControl Method Error on Pages Using MasterPage

If we are to run the above example on a page linked to the masterpage, it will give an error. Because the FindControl method will not find the object inside the contentpage. In case of using MasterPage and FindControl, we can write the codes as follows.

for (int i = 1; i <= 3; i++)
{
    var label = (Label)((ContentPlaceHolder)this.Master.FindControl("MainContent")).FindControl("Label" + i);
            
        label.Text = "hello";
            
}
 
findcontrol method in master page, asp.net find control in content page, using findcontrol with asp net masterpage, replace text in multiple labels with loop, change multiple label using for loop

EXERCISES

There are no examples related to this subject.



COMMENTS




Read 688 times.

Online Users: 1749



changing-multiple-label-controls-using-a-loop