1

I have a asp:GridView inside of an asp:UpdatePanel, which has a column of asp:LinkButton controls.

On the row databound event, the LinkButton gets it's click event handler assigned.

I've tried every way I could find to wire up the click even and none of the events ever fire.

Am I doing something wrong?

aspx:

<asp:UpdatePanel ID="MainUpdatePanel" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:Label ID="lblTest" Text="test" runat="server" />
        <asp:GridView ID="gvClientsArchive" runat="server" AllowSorting="true" DataSourceID="dsClients" 
            OnRowDataBound="gvClientsArchive_RowDataBound" SkinID="gvList"
            AllowPaging="true" PageSize="25" Visible="false">
        ...

Code behind:

protected void gvClientsArchive_RowDataBound(object sender, GridViewRowEventArgs e)
{
    ...
    int company_id = int.Parse(drvRow["company_id"].ToString());
    LinkButton lnkRestore = (LinkButton)e.Row.FindControl("lnkRestore");
    lnkRestore.Click += new System.EventHandler(this.doRestore);

Button handler code:

private void doRestore(object sender, EventArgs e)
{
    lblTest.Text = "restore clicked";
}

I've also tried:

protected void gvClientsArchive_RowDataBound(object sender, GridViewRowEventArgs e)
{
    ...
    LinkButton lnkRestore = (LinkButton)e.Row.FindControl("lnkRestore");
    lnkRestore.Click += delegate
    {
        lblTest.Text = "restore clicked";
    };

1 Answer 1

1

RowDataBound is inappropriate if you want to register event handlers. Use RowCreated:

protected void gvClientsArchive_RowCreated(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType ==  DataControlRowType.DataRow)
    {
        LinkButton lnkRestore = (LinkButton)e.Row.FindControl("lnkRestore");
        lnkRestore.Click += new System.EventHandler(this.doRestore);
    }
}

RowDataBound is triggered only if you Databind the grid not on every postback which is needed since all controls are disposed at the end of the page's lifecycle. It's also too late.

If you use TemplateFields it's easier to register the handler declaratively on the aspx.

Sign up to request clarification or add additional context in comments.

4 Comments

I will try implementing that right now. Why is it inappropriate?
Tim I am using a TemplateField as the column for this LinkButton row. I can see how to add the OnClick in the aspx, but how would I get the context for the rest of the data row, in the click handler event?
@JamesWierzba: you have to cast the Sender to LinkButton(or Control) and then the NamingContainer to GridViewRow. Now you can use row.FindControl to find all other controls in this row.
You save me after googling 1 day

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.