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...!