1

我有一个 aspx 页面,其中包含这段代码来加载从数据库加载的用户控件

Control userControl = new Control();

userControl = LoadControl(userControlName);

((HiddenField)userControl.FindControl("HiddenFieldCategoryID")).Value = categoryID.ToString();

((HiddenField)userControl.FindControl("HiddenFieldNewsID")).Value = newsID.ToString();

((HiddenField)userControl.FindControl("HiddenFieldTypeID")).Value = typeID.ToString();

PlaceHolder3.Controls.Add(userControl);

并且 ascx 有一个输出缓存

<%@ OutputCache Duration=10 VaryByParam="none" %>

当我浏览页面时出现此错误

[NullReferenceException:对象引用未设置为对象的实例。] c:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\AnaweenNews.root\AnaweenNews\ 中的 Content_SectionNews.Page_Load(Object sender, EventArgs e) anaween website\Content\SectionNews.aspx.cs:127 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +50 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627

版本信息:Microsoft .NET Framework 版本:2.0.50727.3615;ASP.NET 版本:2.0.50727.3618

4

1 回答 1

2

从LoadControl返回的类型是PartialCachingControl,请按照PartialCachingControl的使用步骤:

PartialCachingControl userControl = LoadControl(userControlName) as PartialCachingControl;

PlaceHolder3.Controls.Add(userControl);

if(userControl.CachedControl != null)
{
    ((HiddenField)userControl.CachedControl.FindControl("HiddenFieldCategoryID")).Value = categoryID.ToString();    

    ((HiddenField)userControl.CachedControl.FindControl("HiddenFieldNewsID")).Value = newsID.ToString();

    ((HiddenField)userControl.CachedControl.FindControl("HiddenFieldTypeID")).Value = typeID.ToString();
}
于 2012-05-07T10:52:34.617 回答