在我的 default.aspx 页面上,我有一堆带有 ID 和 runat="server"的 div:
<div id="serverOne" runat="server"></div>
<div id="serverTwo" runat="server"></div>
<!--etc...-->
在后面的代码中,我声明了一个具有 2 个值的多维数组(或网格)——第一个是 IP 地址,第二个是服务器名称。
Dim servers = {{"10.0.0.0", "serverOne"}, {"10.0.0.1", "serverTwo"}}
我的问题是,有没有办法可以使用数组中的值从后面的代码中定位我的 div?
For i As Integer = 0 To 1
'This is what I want it to do:
servers(i, 1).InnerHtml = "<span>Testing " & servers(i, 1) & "</span>"
Next
最佳答案
您可以使用 FindControl
来执行此操作页面上的方法。然而,开箱即用FindControl
只看第一层的 child ,不深入 child 的 child 。为了处理这个问题,您需要使用一个允许 FindControl
的辅助方法。递归地搜索控件层次结构以找到所需的控件。将此方法添加到您的代码隐藏中,或者多个页面可以访问的某个共享类中:
Protected Function FindControlRecursive(control As Control, id As String)
If (control.ID = id) Then
Return control
End If
For Each ctl In control.Controls
Dim foundControl = FindControlRecursive(ctl, id)
If (foundControl IsNot Nothing) Then
Return foundControl
End If
Next
Return Nothing
End Function
一旦你有了这个,就很容易找到你的 <div>
只需使用字符串 ID 属性即可。
For i As Integer = 0 To 1
Dim div = CType(FindControlRecursive(Me, servers(i, 1)), HtmlGenericControl)
div.InnerHtml = "<span>Testing " & servers(i, 1) & "</span>"
Next
关于asp.net - 在 ASP.net 中通过 ID 属性访问服务器端控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12007528/