User Control not loading properly

A

anthonyroche

I am trying to achieve the following:

Loading user control dynamically and place the rendered HTML to
screen.

My Scenario: I am loading the control using the following within the
Page_Load from a PageContent.ascx UserControl

Dim _control as Control
_control = LoadControl("News.ascx")
'Then render to screen
Protected _HTML as String = RenderControlToHTML(_control)

This seems to load the user control, but within I News.ascx control I
have a datagrid which should get the TOP 7 news headlines from the DB
and return it to the grid.

[News.ascx]
<%@ Control Language="vb" AutoEventWireup="false"
Codebehind="News.ascx.vb" Inherits="eWiz.NewsHeadlines"
TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
News Datagrid
<asp:DataGrid id="uiNewsHeadlines" runat="server"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<TABLE cellSpacing="2" cellPadding="2" width="100%" border="0">
<TR vAlign="top">
<TD class="dgItem" align="left">
<asp:Label id="uiNewsTitle" runat="Server" Text='<%#
DataBinder.Eval(Container.DataItem,"Title")%>'>
</asp:Label>
</TD>
</TR>
</TABLE>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

Displaying to screen:
I have a function that takes the _control and outputs the 'rendered'
HTML

Private Function RenderControlToHTML(ByVal _control As Control) As
String
'Get the rendered HTML
Dim SB As New StringBuilder
Dim SW As New StringWriter(SB)
Dim htmlTW As New HtmlTextWriter(SW)
_control.Page = Page
_control.EnableViewState = False
_control.RenderControl(htmlTW)
Return SB.ToString()
End Function

My Prob: How do I load the "News.ascx" controls in this instance to
look into the code behind news.ascx and actually populate the datagrid
with news headlines. What I get now is only the "News Datagrid" text
to display.

I have tested news.ascx by placing it within another page not trying
to load it dynamically and it does return the news headlines.

Any help would be great.

Thanks
Anthony
 
R

Robert Koritnik

You already loaded the control. Why do you try to render it this way? Just
put it inside a container where it should reside. Put a Placeholder in place
where your new ascx should be and just call this after your _control =
LoadControl():

_control = LoadControl("News.ascx");
placeholder1.Controls.Add(_control);

voila. Done. Works every single time.
 

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,233
Members
46,820
Latest member
GilbertoA5

Latest Threads

Top