Friday, April 22, 2011

Webpart Preview Page: Event handler not firing in webpart

Today i faced realy strange issue with button event handler in webpart, my webpart created from SharePoint webpart class. This is code

public class MyFirstWebPart : Microsoft.SharePoint.WebPartPages.WebPart
{
 Label userName = new Label();
 Button button;

 protected override void CreateChildControls()
 {
  button = new Button();
  userName.Text = "Sandip";
  button.Text = "Change this text";
  button.Click+=new EventHandler(button _Click);
  this.Controls.Add(userName);
  this.Controls.Add(button);
 }

 protected void button _Click(object sender, EventArgs e)
 {
  userName.Text = "Sandip Patil";
 }
}

I wired up event handler in CreateChildControls method so that was not an issue. Issue is with testing webpart on the page. I was testing webpart on webpart preview page. You can find webpart preview page whenever you select any webpart from webpart gallery page. After 1 hour of wasting time, i created one webpart page and put that webpart inside webpart zone. Thereafter i could see that event handler was firing. Means problem was not with the code but with testing scenario.
Be careful when you test webpart on Webpart Preview page.
Good Bye, Have a nice time...!

3 comments:

  1. Been looking all over for this. Everybody was saying it was a rendering issue and I was adding the event handler during a wrong point in the lifetime of the control. But in the end it was just the the Preview page :-)
    Thanks!

    ReplyDelete
  2. Man... I have spent more than a week. First I used an update panel; I thought it was because of the update panel fixup, then I got rid of the panel to have full postbacks. The same problem, but today I found your post and solved all my problems. Thanks very much for sharing.

    ReplyDelete
  3. U save my life! :)

    Thanks! It's works!

    ReplyDelete