Search code examples
c#asp.netsharepointweb-controlshtmltextwriter

asp:button Created Programmatically: EventHandler does not fire


I am writing a SharePoint web part which will have a simple ASP.NET form. I am using HtmlTextWriter to render the controls. The problem I have is that my button does not seem to be triggering the EventHandler I have assigned it.

I initially declared the button in the CreateChildControls method, and wired the event handler:

{
    Button submitButton;
    submitButton = new Button();
    submitButton.Text = "Go!";
    submitButton.Click += new EventHandler(submitButton_Click);
    Controls.Add(submitButton);
}

I have declared the functionality of the "submitButton_Click" EventHandler:

void submitButton_Click(object sender, EventArgs e)
{
    submitButton.Text = "Good!";
}

I render the controls:

protected override void RenderContents(System.Web.UI.HtmlTextWriter output)
{ 
        RenderChildren(output);
}

Finally, I deploy the web part. It shows up fine in the catalog and when I add it to a page, the control shows up. However, I would assume that when I click the button, its text should change from "Go!" to "Good!" Instead, it does nothing. I'm pretty new to all of these technologies -- C#, Sharepoint, and ASP.NET -- so I'm pretty sure it's a problem with my understanding, but trying different steps from articles all over the net and previous questions here haven't fixed my problem. Thanks for taking a look.

EDIT: I opened the SharePoint page with the web part on it and the button has been created like so:

<input type="submit" name="ctl00$PlaceHolderMain$ctl00$ctl04" value="Go!" />

It looks like the OnClick value has not been added at all, which is what I thought adding the EventHandler would do. Am I trying to add OnClick in a completely wrong way? I also don't understand why the button name does not match what I declared in my code.


Solution

  • Look at this link:

    http://msdn.microsoft.com/en-us/library/ms452873.aspx

    You're overriding the RenderContents method incorrectly, and wiring the click event in the wrong place.