我的webpart事件处理不会在SharePoint中触发

时间:2010-06-03 14:37:25

标签: sharepoint event-handling web-parts

我开始编写复杂的代码然后意识到我的事件处理程序不起作用,所以我用事件处理程序超级简化了一个按钮。请看下面的代码,也许你可以告诉我它为什么不开火?

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
namespace PrinterSolution
{
    [Guid("60e54fde-01bd-482e-9e3b-85e0e73ae33d")]
    public class ManageUsers : Microsoft.SharePoint.WebPartPages.WebPart
    {
        Button btnNew;


        protected override void CreateChildControls()
        {
            btnNew = new Button();
            btnNew.CommandName = "New";
            btnNew.CommandArgument = "Argument";
            btnNew.Command += new CommandEventHandler(btnNew_Command);
            this.Controls.Add(btnNew);
        }

        void btnNew_Command(object sender, CommandEventArgs e)
        {
            ViewState["state"] = "newstate";
        }



        //protected override void OnLoad(EventArgs e)
        //{
        //    this.EnsureChildControls();
        //}

    }
}

1 个答案:

答案 0 :(得分:2)

我有类似的问题。在我的情况下,按钮包含在一个面板中,虽然父控件上的按钮正常工作,但子面板控件上的按钮却没有。

事实证明,您需要在子面板中的EnsureChildControls方法中调用OnLoad,以确保在life cycle of the page中尽早调用CreateChildControls,以便控制可以回应事件。这在this answer here中简要描述,这是我发现问题解决方案的地方。

按照此说明,我刚刚将以下代码添加到我的面板控件中:

    protected override void OnLoad(EventArgs e)
    {
        EnsureChildControls();
        base.OnLoad(e);
    }

我注意到在论坛中似乎存在很多关于这个问题的混淆,所以为了证明这是有效的,我在我的代码中添加了trace语句。以下是案例之前和之后的结果。请注意,Survey list creating child controls的位置从PreRender事件内移动到Load事件中。

在:

Before making the change to call EnsureChildControls in the OnLoad override

后:

After making the change to call EnsureChildCOntrols in the OnLoad override which shows the child controls being created in the correct place in the page life cycle