R – Sharepoint 2007 – Button OnClick event not firing

sharepointwss-3.0

Whilst writing a custom webpart for use in Sharepoint 2007 / WSS 3.0 I've come across a strange problem – when a button on my webpart is clicked, the event handlers are not firing.

Following the advise MSDN, Inside Sharepoint Services 3.0 and of course stackoverflow answers, I've overridden the CreateChildControls() method of System.Web.UI.WebControls.WebParts.WebPart.

The method looks like this:

protected override void CreateChildControls()
{

    // Get the ID from the master (pseudocode here to keep it short)
    if(ICrediteurIdProviderReference == null)
    {
        // We must have the detail-id or we can't load the form
        return;
    }

    // Call base
    base.CreateChildControls();

    // ** Creation of the rest of the form removed for clarity **

    // Create button
    Button saveButton = new Button();
    saveButton.ID = "SaveButton";
    saveButton.Text = "Save";
    // saveButton.CommandName = "Save";
    // saveButton.CommandArgument = "";

    // Register event handler
    saveButton.Click += new EventHandler(saveButton_Click);

    // Add button to page
    this.Controls.Add(saveButton);

}

For clarity I've removed the initiation of the rest of the form, as well as the creation of an HTML table within which the form is placed.

My event handler looks like this:

void saveButton_Click(object sender, EventArgs e)
{
    System.Diagnostics.Debug.WriteLine("saveButton_Click fired..");
}

Yup, that's my default 'simple debug' event handler.

So far I've tried following these suggestions, but with no luck:

  • Setting CommandName and CommandArgument on the button (see commented out code)
  • Creating buttons in the OnInit() method instead of in CreateChildControls()

Starting to tear my hair out, but I assume it's something really simple that I've missed. Any help would be greatly appreciated 🙂 🙂

Best Answer

Corrected thanks to comments :)

It looks like CreateChildControls is called twice. The first time is before the binding of the provider values. The second time is after the binding.

For the events to fire, the controls must be added the very first time CreateChildControls is called. The state must be loaded into the controls the second tiem CreateChildControls is called (i.e. once we have the record-id from the master via ICrediteurIdProviderReference).

My new CreateClientControls() looks like this:

protected override void CreateChildControls()
{

    if (controlsLoaded == false)
    {
        LoadControls();
    }

    if (myProviderInterface != null)
    {
        LoadState(myProviderInterface.CrediteurId);
    }

}

controlsLoaded being a local boolean, which is set to true when LoadControls() has completed.

Strange how writing your problem out properly then reading it back can actually help you solve it :)

Related Topic