如何在页面加载上获取控件ID

时间:2012-04-18 18:22:55

标签: asp.net vb.net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
    Dim lbl_Date As New Label
    Dim i as int16
    i = 20
    While (i < i + 1)
       lbl_Date = TryCast(Page.FindControl("lbl_Date" + i.ToString), Label)
       lbl_Date = "Value"
   i = i + 1
   End While
End Sub

这在lbl_Date变量中返回Nothing。如果我不在Page_Load中使用它,它可以正常工作。仅在Page_Load中它不起作用。任何解释 ::::我想在这里做的是。我有100个标签名称是lable1到lable100。我可以做像label1 = Value和label2 = Value等等,但我试图放入循环所以我有更少的代码。只是为了信息...... 这段代码工作但不在Page_Load中,我想每个人都在寻找代码,但这与页面生命周期有关

1 个答案:

答案 0 :(得分:-1)

<asp:content runat="server" id="leftcontent" contentplaceholderid="LeftSidePanel" xmlns:asp="#unknown"> 
<div id="mydiv" runat="server"> 
<asp:linkbutton id="Lnk_Heading1" runat="server"> </asp:linkbutton>
<asp:label id="lbl_Date1" runat="server"> </asp:label>
<asp:label id="lbl_Detail1" runat="server"> </asp:label>
<asp:button id="Button1" runat="server" text="Button" /> 
</div> 
</asp:content>

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
Dim lbl_Date As New Label 
Dim i as int16 i = 20 
While (i &lt; i + 1) lbl_Date = TryCast(Mydiv.FindControl("lbl_Date" + i.ToString), Label) 
lbl_Date = "Value" 
i = i + 1 
End While 
End Sub 

问题是,我没有在我的aspx页面中使用DIV。当我把我的代码放在div中并在代码隐藏中使用div的引用时,它就可以工作了。