将usercontrol动态添加到updatepanel

时间:2012-11-12 15:23:55

标签: vb.net dynamic user-controls updatepanel

我有一个包含updatePanel的页面....

<asp:UpdatePanel runat="server" ID="up1" UpdateMode="Conditional" OnLoad="up1_Load">
  <ContentTemplate>
  </ContentTemplate>
</asp:UpdatePanel>

我还有一个usercontrol(为了这个例子,这里大大简化了)......

UserControl标记:

<%@ Control Language="vb" AutoEventWireup="false" Codebehind="CtlParts.ascx.vb" Inherits="myProj.myProj.UserControls.ctlParts" TargetSchema="http://schemas.microsoft.com/intellisense/ie5"%>  
<asp:textbox runat="server" id="txtTest"></asp:textbox>

我正在尝试将usercontrol动态添加到更新面板(following this guide)....

表单VB

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim ctl As New UserControls.ctlParts
    ctl.ID = "ctlParts1"
    up1.ContentTemplateContainer.Controls.Add(ctl)
End Sub

它似乎工作,因为没有错误,我可以在更新面板的load事件中访问usercontrol本身....

表单VB

Public Sub up1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles up1.Load  
         'Finds this control ok
         Dim ctl As UserControls.ctlParts = DirectCast(sender, System.Web.UI.UpdatePanel).FindControl("ctlParts1") 
         ctl.getTextBoxContent()    
    End Sub

但是,我无法访问用户控件上的任何控件.....

Usercontrol VB

Public Sub getTextBoxContent()
    return txtTest.text 'This throws an error- txtTest is nothing
End Sub

任何人都知道为什么会这样。我做错了什么?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。

您需要使用LoadControl方法。所以,在Page_Load:

Dim ctl As UserControls.ctlParts=CType(LoadControl("ctlParts.ascx"), ctlParts)

(希望这有助于某人。)