Dynamic ID name in ASP.NET VB.NET
I have about 20 asp:labels in my ASP page, all with ID="lbl#", where # ranges from 0 to 22. I want to dynamically change what they say. While I could write
lbl1.Text = "Text goes here"
for all 23 of them, I'd like to know if there is a way to loop through all of them and change their text.
I thought of creating an array with all my labels, and then just do a For Each loop, but I also have to c开发者_如何学运维heck if the element exists with IsNothing before I change its text, so I got stuck there.
If anyone can help me, I'd really really appreciate it!
Thank you so so much for your help!!
You can dynamically look up controls on the page by using the System.Web.UI.Page.FindControl()
method in your 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
Something like this may work, but you would likely need to tweak it (its from memory, so its not exactly 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 jQuery selectors.
精彩评论