Render Control to string

I programmatically created a control and now want to get the rendered HTML as a string. How do I do it

I tried:
        Dim MyRenderedOutput As String = ""
        Dim SW As New System.IO.StringWriter(MyRenderedOutput)
        Dim hstw As New HtmlTextWriter(SW)
        MyControl.RenderControl(hstw)

But I get an Error:
System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.IFormatProvider'.

Your help is very much appreciated
Beat



Answer this question

Render Control to string

  • Bart_p

    Many Thanks, Vikram.

    Wounderful - It works well for TextBox, Labels, Dorpdown.

    It does not work for TreeView.
    I get the Error:
    System.NullReferenceException: Object reference not set to an instance of an object.
    What do I need to do for the more complex objects

    Here is the code I tried:
    Dim MyControl As New TreeView
    MyControl.ToolTip = "My TreeVeiw Control"
    MyControl.ID = "MyTVTest"
    Dim NN As New TreeNode()
    'newNode.PopulateOnDemand = True
    NN.Text = "treenode TEXT 1"
    NN.Value = "Treenode Value 1"
    NN.ToolTip = "Treenode Tooltip 1"
    MyControl.Nodes.Add(NN)

    Dim sbHtmlContent As New System.Text.StringBuilder()
    Dim objStringWriter As New System.IO.StringWriter(sbHtmlContent)
    Dim objHtmlTextWriter As New HtmlTextWriter(objStringWriter)
    MyControl.RenderControl(objHtmlTextWriter)    <<<< Error occurs here
    Dim strTextBoxHtml As String = sbHtmlContent.ToString()

    Remark: As long as I do not add Nodes to the TreeView - it works well...

    Beat


  • sdknewbie

    Hi Beat,

    Here's a code snippet based on .NET 2.0 B2 with VB 2005 - I am assuming a TextBox control...
    -------------------------------------------------------------------
    CODE SNIPPET
    -------------------------------------------------------------------

    Dim MyControl As New TextBox
    Dim sbHtmlContent As New System.Text.StringBuilder()
    Dim objStringWriter As New System.IO.StringWriter(sbHtmlContent)
    Dim objHtmlTextWriter As New HtmlTextWriter(objStringWriter)
    MyControl.RenderControl(objHtmlTextWriter)
    Dim strTextBoxHtml As String = sbHtmlContent.ToString()
    -------------------------------------------------------------------

    Regards,
    Vikram


  • Edimilson Simionato

    Hi Beat,

    You are correct - the same exception was re-created for me as well when I tried your code snippet. I'd recommend that you use a custom XML to store the Nodedata of a Treeview.

    Regards,
    Vikram

    Please mark the reply as answer if it helped!


  • Render Control to string