且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Asp.net Usercontrol LoadControl 问题

更新时间:2023-12-06 10:33:16

我也尝试了以下代码 - 产生相同的结果(即 lblTitle 和 lblDescription 均为空)

I have tried the following code as well - which yields the same result (i.e. both lblTitle and lblDescription are null)

protected void Page_Load(object sender, EventArgs e)
{
    if (_ErrorMessage != null)
    {
        lblTitle.Text = _ErrorMessage.Message;
        lblDescription.Text = _ErrorMessage.Description;
    }
}

我了解到 LoadControl 函数将它正在加载的控件带到它所包含的页面的当前状态".因此 Init、Page_Load 等都作为 LoadControl 调用的一部分运行.

I had the understanding that the LoadControl function brought the control it is loading up to the current 'state' of the page onto which it is being included on. hence the Init, Page_Load etc are all run as part of the LoadControl call.

有趣的是,这个(未答复的)asp.net 论坛帖子与我遇到的问题相同.

Interestingly this (unanswered) asp.net forums post exhibits the same problem as I am experiencing.

MSDN 论坛帖子

另外 - 来自 MSDN:

Additionally - From the MSDN:

当您将控件加载到容器控件中时,容器会引发所有已添加控件的事件,直到它赶上当前事件为止.但是,添加的控件无法赶上回发数据处理.要使添加的控件参与回发数据处理(包括验证),必须将控件添加到 Init 事件而不是 Load 事件中.

When you load a control into a container control, the container raises all of the added control's events until it has caught up to the current event. However, the added control does not catch up with postback data processing. For an added control to participate in postback data processing, including validation, the control must be added in the Init event rather than in the Load event.

因此 LoadControl 不应该正确初始化控件吗?

Therefore shouldn't LoadControl correctly initalise the control?

好的,所以我在这里回答我自己的问题..

Ok, so I'm answering my own question here ..

我在这里 找到了我链接到的论坛帖子的回答版本

I found an answered version of the forum post I linked to above Here

基本上答案是 LoadControl( type, params ) 无法推断要解析的page infront" ascx,因此它不会打扰初始化任何控件.当您使用 LoadControl( "ascx path" ) 版本时,它会在前面给出页面,因此会执行所有解析和初始化.

Essentially the answer is that the LoadControl( type, params ) cannot infer the 'page infront' ascx to parse and hence it doesn't bother initalising any of the controls. When you use the LoadControl( "ascx path" ) version it is given the page infront and hence does all the parsing and initalision.

总而言之,我需要更改初始化控件的代码并将其拆分为单独的部分.即

So in summary I need to change the code which is initalising the control and split it into seperate parts. I.e.

Control ErrorCntrl = LoadControl("ErrorDisplay.ascx");
ErrorCntrl.ID = SomeID;
(ErrorCntrl as ErrorDisplay).SetErrorMessage = MessageDetail;
divErrorContainer.Controls.Add(ErrorCntrl);

它应该可以正常工作.它不像我之前的尝试那样整洁,但至少它会工作.

And it should work ok.. It isn't as neat as my previous attempt, but at least it will work.

我仍然愿意接受改进上述内容的建议.

I am still open to suggestions to improve the above.

干杯