代码之家  ›  专栏  ›  技术社区  ›  Brad

VB.NET以编程方式在标记之间添加代码

  •  0
  • Brad  · 技术社区  · 16 年前

    我有一个自定义控件,它在异步回发上为我做了一些工作。通常,我会使用ASPX页面上的以下代码直接从表示端调用控件:

    <mytag:CustomControl runat="server">
        html (or other text) goes here
    </mytag:CustomControl>
    

    但是,在我当前的应用程序中,我需要从codebehind动态创建控件,使用类似于以下代码的代码:

    Dim myControl As myClass.CustomControl = New myClass.CustomControl
    myControl.ID = "someID"
    myControl.?????? = "html (or other text) goes here"
    Me.Controls.Add(myControl)
    

    当动态地将控件添加到页面时,如果控件是以正常的非动态方式添加的,如何添加通常在开始和结束标记之间的信息?

    谢谢

    以下是实际控制:

    Protected Overloads Overrides Sub Render(ByVal writer As HtmlTextWriter)
        Dim scriptmanagerPage As ScriptManager = ScriptManager.GetCurrent(Page)
        If scriptmanagerPage Is Nothing Then
            'Do nothing
        Else
            'See if we are in a postback
            If scriptmanagerPage.IsInAsyncPostBack Then
                'We are in a postback; register the script
                Dim stringbuilderWorking As New StringBuilder()
                MyBase.Render(New HtmlTextWriter(New StringWriter(stringbuilderWorking)))
                Dim stringScript As String = stringbuilderWorking.ToString()
                ScriptManager.RegisterStartupScript(Me, GetType(ScanWorkXAJAX), UniqueID, stringScript, False)
            Else
                'Not in a postback
                MyBase.Render(writer)
            End If 'In an async postback
        End If 'Scriptmanager present
    
    End Sub
    
    4 回复  |  直到 16 年前
        1
  •  3
  •   zincorp    16 年前

    你说的数据是什么意思?更多控制?

    你可以使用

      myControl.Controls.Add(childControlHere);
    

    澄清问题后编辑:

    添加文本控件。即

    myControl.Controls.Add(new LiteralControl("<b>hello world</b><script type='text/javascript'>alert('hi');</script>"));  
    
        2
  •  0
  •   Kevin Goff    16 年前

    您的意思是在动态控件中查找数据并将其附加到控件中吗?

    可以使用webcontrol.find control方法查找嵌入在自定义控件中的控件,然后可以通过其属性添加数据。 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.findcontrol.aspx

        3
  •  0
  •   Kevin Goff    16 年前

    这取决于正在使用的自定义控件的属性。您可能需要绑定到要显示的模板,以便触发事件,这实际上取决于您的特定控件。

        4
  •  0
  •   Brad    16 年前

    可以使用文本控件来完成此操作。

    以上代码加:

    Dim myLiteral As LiteralControl = New LiteralControl
    myLiteral.ID = "myLiteral"
    myLiteral.Text = "html (or some other text) goes here"
    myControl.Controls.Add(myLiteral)