Forum Moderators: open
I have an annoying bug, I have built one usercontrol called BlogPost.ascx and one called BlogPostWithComments.ascx which loads the BlogPost one and then adds some extra features to the output.
If I refer to a variable in the .ascx file (i.e. BlogPost1.BlogId) it works fine, but if I try to use this in the class file, despite it coming up in the Visual Studion intellisense it returns a null value.
BlogPostWithComments.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="BlogPostWithComments.ascx.cs" Inherits="managed_content_usercontrols_BlogPostWithComments" %>
<%@ Register src="BlogPost.ascx" tagname="BlogPost" tagprefix="uc1" %>
<uc1:BlogPost ID="BlogPost1" runat="server" />
<%=BlogPost1.BlogId %>
BlogPostWithComments.ascx.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.IO;
using System.Web;
using System.Web.Caching;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
//
public partial class managed_content_usercontrols_BlogPostWithComments : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("[" + BlogPost1.BlogId + "," + BlogPost1.PostAuthor + ",");
}
}
Does anyone have any idea why? The <%=BlogPost1.BlogId%> outputs fine.
Thanks.
<%=BlogPost1.BlogId %> will automaticly convert this to
Response.Write(BlogPost1.BlogId.ToString());
Example Below
<%@ Control Language="C#" AutoEventWireup="true" %>
<table border="1">
<tr><td><%=BlogID%></td><td><%=PostAuthor%></td></tr>
</table>
<script runat="Server" language="C#">
private Guid _BlogID = Guid.NewGuid();
public Guid BlogID
{
get
{
return _BlogID;
}
set
{
_BlogID = value;
}
}
private object _PostAuthor = new object();
public object PostAuthor
{
get
{
return _PostAuthor;
}
set
{
_PostAuthor = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("[" + this.BlogID.ToString() + "," + this.PostAuthor.ToString() + "]");
}
</script>
I've tried Marcel's suggestion and bizarrely while the text in the Page_PreRender doesn't work the text in the Page_Load does.
So adding the code above generates the text:
[,,[173,Mr Blogger,
Ocean10000, I'm having a look at your suggestion now.
What's most likely happening is that you are trying to get the values from BlogPost in the Page_Load event before the UserControl BlogPost itself has loaded. By moving the code to PreRender, BlogPost has already loaded and you are inserting the values just before it is being rendered to HTML.