Custom command button in ASP gridview C#

A powerful feature to add your own button to the gridview and have custom commands. Most basic is you would want to pass the id of the record so you can do stuff to it.

In your gridview add a templatefield with a button as so…

<asp:TemplateField HeaderText="Actions">
     <ItemTemplate>
            <asp:Button runat="server" CssClass="btn btn-sm btn-danger" Text="Do Something" CommandName="CustomFunction" CommandArgument='<%# Eval("Id") %>'  /> 
     </ItemTemplate>
</asp:TemplateField>

 

Then you use the RowCommand event of the gridview to do what you need to…

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "CustomFunction")
            { string recordId = e.CommandArgument.ToString(); 
               // do what ever you need to do with the record id
             }
        }

Leave a Reply