User Control Output to a String

  • Thread starter J. Shane Kunkle
  • Start date
J

J. Shane Kunkle

Hello - Please help,



I am having trouble copying the output of a User Control into a string.



For example - assume I have defined the following user control:



<%@ Control %>

<script runat="server">

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

lblInput.Text = "The Page Load Event executed"

End Sub



</script>

<asp:label id="lblInput" runat="server" />



I have defined a generic function in another assembly that is called from a
button post back event. This function has to be able to instantiate any
user control whose URL is passed in and return it's rendered output in a
string. Note: the User Control specified by the input URL is not
necessarily loaded on the current page (which is the case in all the
examples I have seen).



Private Function AscxToString(ByVal url as string) as String

Dim objUserControl As New System.Web.UI.UserControl



Dim sw As StringWriter = New StringWriter

Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)



'Create a new Page instance and a server-side form

Dim p As New Page

Dim hf As New HtmlForm



objUserControl = objUserControl.LoadControl(url)



'Build up the control hierarchy

p.Controls.Add(hf)

hf.Controls.Add(objUserControl)



'Call the page's RenderControl() method

p.DesignerInitialize()

objUserControl.RenderControl(hw)



p = Nothing



Return sw.ToString()

End Function



However whenever I execute the above code and pass in a URL to the ascx file
of the above user control - it returns the following html:



<span id="_ctl1_lblLanguage"></span>



It's like the User Control/Page is not going thru the life-cycle properly
and the Page_Load event is not being raised. (the string "The Page Load
Event executed" is never output)



I have tried creating my own page class that inherits from Page so I can
explicitly call OnLoad (etc) and I have tried adding the user control to the
current page - but that hasn't worked. Is there an easy way to force a page
or control to traverse all the steps of the life cycle?



Or maybe I'm going about this all wrong? Does anyone have a better idea of
how to programmatically create and get the rendered output of a user
control? What am I doing wrong?



Thanks in advance,

J. Shane Kunkle
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top