My webpart event handling does not fire in SharePoint

跟風遠走 提交于 2019-12-23 19:54:22

问题


I started coding something complicated and then realized my event handlers don't work, so I super simplified a button with an event handler. Please see the code below and maybe you can tell me why it doesn't fire?

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:


I had a similar problem. In my case the button was contained in a panel and although buttons on the parent control worked correctly the button on the child Panel control didn't.

It turns out that you need to call EnsureChildControls in the OnLoad method in the child panel to ensure that CreateChildControls is called early enough in the life cycle of the page so that controls can respond to events. This is described briefly in this answer here which is where I discovered the solution to my problem.

Following this instruction I just added the following code to my panel control:

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

I notice that there appears to be a lot of confusion about this issue in the forums so to demonstrate that this works I added trace statements to my code. Below are the results from the before and after cases. Note that the position of Survey list creating child controls moves from within the PreRender event to within the Load event.

Before:

After:



来源:https://stackoverflow.com/questions/2966928/my-webpart-event-handling-does-not-fire-in-sharepoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!