Dynamic Identifier Name in ASP.NET VB.NET

I have about 20 asp: labels on my ASP page, all with ID = "lbl #" , where # ranges from 0 to 22. I want to dynamically change what they say. Although I could write

lbl1.Text = "Text goes here" 

for all 23 of them, I would like to know if there is a way to iterate over all of them and change their text.

I thought about creating an array with all my labels, and then just looped For everyone , but I also need to check if this element exists with IsNothing. I'm changing my text, so I'm stuck there.

If anyone can help me, I really really appreciate that!

Thank you so much for your help!

+4
source share
2 answers

You can dynamically search for controls on a page using the System.Web.UI.Page.FindControl() method in the Page_Load method:

 Dim startIndex As Integer = 0 Dim stopIndex As Integer = 22 For index = startIndex To stopIndex Dim myLabel As Label = TryCast(FindControl("lbl" + index), Label) If myLabel Is Nothing Then Continue For End If myLabel.Text = "Text goes here" Next 
+2
source

Something like this might work, but you will probably have to fine-tune it (from memory, so its not 100% syntactically correct)

 For Each _ctl as Control In Me.Controls() If (TypeOf(_ctl) Is Label) = False Then Continue For End If 'add additional filter conditions' DirectCast(_ctl, Label).Text = "Text Goes Here" Next 

You can also do something similar on the client side using the jQuery selector .

0
source

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


All Articles