Why my event binding fails?

141 Views Asked by At

I have a link button on the .aspx page :

<asp:LinkButton runat="server" ID="lnkSynEvent" Text="Export Event to Outlook"></asp:LinkButton>

and a method on code behind page :

protected void lnkSynEvent_Click(object sender, EventArgs e, DataTable data)
        {}

Now at the runtime I am trying to bind the event to the Link Button, inside a function

lnkSynEvent.Click +=new EventHandler((sender,args) => lnkSynEvent_Click(sender,args, eventData));

But when user click on the Link button it doesn't fire the Click event. Not sure why.

Please help.

2

There are 2 best solutions below

3
On

You need to attach the event back on every post back. In other words, if you attach an event inside if (!IsPostBack), it wont' fire.

protected void Page_Load(object sender, EventArgs e)
{
  var data = new DataTable();
  lnkSynEvent.Click += new EventHandler((s, a) => lnkSynEvent_Click(s, a, data));
}

protected void lnkSynEvent_Click(object sender, EventArgs e, DataTable data)
{

}

The following code won't fire click event

protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    var data = new DataTable();
    lnkSynEvent.Click += new EventHandler((s, a) => lnkSynEvent_Click(s, a, data));
  }
}
0
On

You need to add an OnClick attribute to the LinkButton tag (this is setting it up at compile time).

<asp:LinkButton runat="server" OnClick="lnkSynEvent_Click" ID="lnkSynEvent" Text="Export Event to Outlook"></asp:LinkButton>

MSDN Link