Set Server Side OnClick() event Programmatically

Posted by Corey O. on Stack Overflow See other posts from Stack Overflow or by Corey O.
Published on 2010-04-17T01:23:41Z Indexed on 2010/04/17 1:33 UTC
Read the original article Hit count: 403

I am looking for a way to programmatically set the OnClick event handler for a TableCell object. The ASP equivalent of what I'm trying to do will look like this:

<asp:TableCell OnClick="clickHandler" runat="server">Click Me!</asp:TableCell>

In the above example, "clickHandler" is a server-side function defined in the .cs CodeBehind.

public virtual void clickHandler(object sender, EventArgs args) {...}

However, for my situation, this TableCell object needs to be created dynamically, so setting it in an ASP tag is not an option. I am trying to do something like the following in the CodeBehind:

System.Web.UI.WebControls.TableRow row = new System.Web.UI.WebControls.TableRow();
System.Web.UI.WebControls.TableCell cell = new System.Web.UI.WebControls.TableCell();
cell.Text = "Click Me!";
cell.Attributes.Add("onClick", "clickHandler");
row.Cells.Add(cell);

Unfortunately, in this situation:

cell.Attributes.Add("onClick", "clickHandler");

the "clickHandler" only works as a client-side javascript function. What I'm looking for is a way to link the server-side clickHandler() function, defined in the .cs CodeBehind, to this table cell.

After an afternoon of searching, I have been unable to come up with a working solution. Thanks in advance for any help.

© Stack Overflow or respective owner

Related posts about tablecell

Related posts about onclick