C# – Difference in OnClick for ImageButton inside a GridView vs. regular ImageButton

asp.netcgridviewimagebutton

I'm working on a ASP.NET/C# project, and have a GridView control. One of the columns is a TemplateField/ItemTemplate with an ImageButton inside. During the OnClick event, I make a panel visible. When doing this with a regular ImageButton, the page reloads and the panel is visible. This doesn't happen with my ImageButton inside of the GridView. Does anyone know how I can make it do so, or why this is the case?

Thanks for your time, please let me know if you have any questions.

Here's the relevant asp definition

<asp:TemplateField ItemStyle-Width="90px"  ItemStyle-VerticalAlign ="Bottom" ItemStyle-HorizontalAlign ="Center" HeaderText="Add Alias">
                <HeaderStyle Font-Bold="True" Font-Size="11px" VerticalAlign="Bottom"/>
                    <ItemTemplate>
                        <asp:ImageButton ID ="btnAddAliasHeader" runat="server" ImageUrl="~/img/AddAlias.gif" onclick="btnAddAlias_Click" />
                 </ItemTemplate>
                </asp:TemplateField>

And here's the C# for the OnClick function.

protected void btnAddAlias_Click(object sender, EventArgs e)
{
    ImageButton btnAddAlias = (ImageButton)sender;
    GridViewRow row = (GridViewRow)btnAddAlias.Parent.Parent;
    int rowIndex = row.RowIndex;

    lblSelectedCity.Text = gvResults.Rows[rowIndex].Cells[0].Text;
    lblSelectedCountry.Text = ddlCountry.Text;
    pnlAddAlias.Visible = true;

}

I added the OnRowCommand event and made the panel visible there, however it still doesn't show up. I think it may have something to do with postback, because if I then click the button outside of the gridview, on the reload then the panel from the button inside the gridview shows up fine.

Edit: I'm an idiot and left out that all of this is happening in an updatepanel.

Best Answer

Buttons, ImageButtons and LinkButtons do not fire Click events when they are in a control template like you describe. (Edit: unless used with the OnClick property of the control) Instead, the containing control fires an event, in the case of the GridView it is a RowCommand event. Use the CommandName and CommandArgument properties of your button to determine the proper action to take in the event handler as shown below:

Markup:

<asp:LinkButton ID="LinkButton1" runat="server" CommandName="DoStuff" CommandArgument='<%# Eval("RecordID") %>' Text="DoStuff"></asp:LinkButton>

Code:

Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
    If e.CommandName = "DoStuff" Then
        'Do something with e.CommandArgument'
    End If
End Sub
Related Topic