ASP.NET VB.NET 中的动态 ID 名称

发布于 2024-10-19 06:57:04 字数 389 浏览 0 评论 0 原文

我的 ASP 页面中有大约 20 个 asp:labels,全部带有 ID="lbl#",其中 # 的范围从 0 到 22。我想动态更改它们的内容说。虽然我可以

lbl1.Text = "Text goes here"

为所有 23 个内容编写内容,但我想知道是否有办法循环遍历所有内容并更改其文本。

我想用所有标签创建一个数组,然后执行 For Each 循环,但在更改其之前,我还必须使用 IsNothing 检查该元素是否存在文本,所以我被困在那里。

如果有人可以帮助我,我真的很感激!

非常感谢您的帮助!

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 check 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!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

饮湿 2024-10-26 06:57:04

您可以使用 Page_Load 方法中的 System.Web.UI.Page.FindControl() 方法动态查找页面上的控件:

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

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
剪不断理还乱 2024-10-26 06:57:04

像这样的东西可能会起作用,但你可能需要调整它(它来自记忆,所以它在语法上并不完全100%正确)

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

你也可以在客户端使用 jQuery 选择器

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文