【问题标题】:Controls on Control loaded by LoadControl are null on Page_Load由 LoadControl 加载的 Control 上的控件在 Page_Load 上为空
【发布时间】:2015-01-22 11:46:02
【问题描述】:

我有一个由 LoadControl 加载的用户控件,并且在所述用户控件背后的代码上,我尝试访问一个为 null 的控件。

Default.aspx:

protected void Page_Load(object sender, EventArgs e){

    // ...

List<String> usersCustomers = custRepo.GetUserCustomers(currentUser.ID).Select(s => s.custName).ToList();
    FileTrackingControl fileTrackingControl = (FileTrackingControl)LoadControl(typeof(FileTrackingControl), new object[] { usersCustomers, currentUser });
    dashboardWidgetPanel.Controls.Add(fileTrackingControl);

    // ...

}

FileTrackingControl.ascx:

public partial class FileTrackingControl : System.Web.UI.UserControl
{
    List<string> _custNames;
    User _currentUser;

    public FileTrackingControl(List<string> custNames, User currentUser)
    {
        this._custNames = custNames;     
        this._currentUser = currentUser;
    }

    protected void Page_OnInit(object sender, EventArgs e)
    {

        StatToCwData scData = new StatToCwData();

        GridView fileTrackingResultsFC = (GridView)FindControl("fileTrackingResults");

        // CRASH HERE. NPE: fileTrackingResults is NULL
        fileTrackingResults.DataSource = scData.GetControlData(6, _currentUser, _custNames);
        fileTrackingResults.DataBind();
    }
}

【问题讨论】:

    标签: c# asp.net webforms user-controls


    【解决方案1】:

    基于你确实有一个 ID 为 fileTrackingResults 的网格视图(它总是值得仔细检查!),那么我认为你正在尝试在创建控件之前访问它们(我记得 MS 说你不应该在 oninit 事件中访问控制树)。在您的情况下,可能只是将代码移动到 Page_Load 事件中,或者如果您需要保留 Page_Load 以用于其他类型的功能,则手动创建 Page_PreLoad 事件并映射事件处理程序。或者,您可以在您的用户控件上创建一个 LoadData 类型的方法并手动触发它(使用接口来声明该方法,以便您可以在其他代码中滚动它)。

    【讨论】:

    • 它现在在 OnInit 中,因为 Load 和 PreLoad 不起作用,我在搜索的其他一些堆栈帖子中看到了它。然而,这也没有奏效。我是接口新手,接口如何让我滚动到其他代码?
    • 如果您以前没有使用过接口,它可能不会为这个特定示例添加任何内容。但是基于您可能有其他几个组件,所有组件都使用 LoadControl 加载,然后通过使用接口,您可以定义一个通用方法名称,而无需在页面中编写不同的处理。
    • 最简单的解决方案是在您的控件上创建一个 LoadData 方法,将代码移到那里,然后在调用 LoadContol 之后立即调用您的 LoadData 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多