How do you bind your GridView ? Do you use data source control? If you contact manually during Page_Load , it is possible that, since the grid is bound to each round trip, the event handler is not caught properly. If so, you can try something like:
protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack) {
Can you post a sample anchor code to jump with your markup?
If you decide to really fix the problem, you can connect to the RowDataBound event in the Grid, find the button manually and add the handler to the code behind. Something like:
markup fragment:
<asp:GridView ID="gvTest" runat="server" OnRowDataBound="gvTest_RowDataBound" />
code behind:
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e) { if(e.Row.RowType == DataControlRowType.DataRow) { //find button in this row LinkButton button = e.Row.FindControl("DeleteButton") as button; if(button != null) { button.Click += new EventHandler("DeleteButton_Click"); } } } protected void DeleteButton_Click(object sender, EventArgs e) { LinkButton button = (LinkButton)sender; // do as needed based on button. }
I'm not sure what the purpose of the button is, but assuming it is a line delete button, you may not want to use this approach as in an event handler, you do not have direct access to the line in the question, how would you use the RowCommand event.
Is there a reason you are using the Template field? Vs say a ButtonField ? If you use ButtonField , you can connect to the RowCommand event.
markup fragment:
<asp:GridView ID="gvTest" runat="server" OnRowCommand="gvTest_RowCommand"> <columns> <asp:buttonfield buttontype="Link" commandname="Delete" text="Delete"/> .... </columns> </asp:GridView>
code behind:
protected void gvTest_RowCommand(object sender, GridViewCommandEventArgs e) { if(e.CommandName == "Delete") { //take action as needed on this row, for example int rowIndex = Convert.ToInt32(e.CommandArgument); GridViewRow currentRow = (sender as GridView).Rows[rowIndex]; //do something against the row... } }
You might want to check out the MSDN docs on some of these topics:
EDIT:
To answer your question on ButtonField - yes, I donโt understand why you couldnโt still deal with the button field. Here's a snippet to find the button field during row data and hide it (unchecked, but I think it will work ...)
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) {