开发者

My webpart event handling does not fire in SharePoint

开发者 https://www.devze.com 2023-01-01 22:04 出处:网络
I sta开发者_如何学Gorted 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

I sta开发者_如何学Gorted 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();
        //}

    }
}


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:

My webpart event handling does not fire in SharePoint

After:

My webpart event handling does not fire in SharePoint

0

精彩评论

暂无评论...
验证码 换一张
取 消