How to put a button in an ASP.NET gridview header?

All I want to do is put the asp: button in the gridview header. Let's say you have a grid with three columns - id, name, family. So, instead of the [id, name, family] header, I want it to be [id, name, asp: button] - so the button will have this action, of course.

Thanks, Roman.

+6
button
source share
2 answers

The approach you need to take is to make the template field the desired GridView column. When you use the template fields, you can embed any asp.net controls in each main section of the gridview control (header, element, footer, etc.). I have not tested this, but basically it looks like this:

<asp:GridView ID="Gridview1" runat="server"> <Columns> <asp:BoundField DataField="yourDbColumnName" HeaderText="id" /> <asp:BoundField DataField="yourDbColumnName" HeaderText="name" /> <asp:TemplateField> <HeaderTemplate> <asp:Button runat="server" ID="btnFamily" CommandName="FamilyClicked" /> </HeaderTemplate> <ItemTemplate> <asp:Literal runat="server" ID="litFamily" Text='<%# EVAL("YourDbColumnValue") %>'></asp:Literal> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> 

To โ€œcaptureโ€ a button click event and do something with it, you need to use the GridView RowCommand event (here the starting point is again unchecked):

  Protected Sub Gridview1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles Gridview1.RowCommand If e.CommandName = "FamilyClicked" Then ' they clicked by grid view header asp:button control... Response.Write("TEST") End If End Sub 

The magic here is to assign the CommandName property of your button (in this case, I set it to "FamilyClicked", but that may be all you want).

Here are some more basics of Template Field technology that GridView uses - link text

Hope this helps.

+11
source share

this is actually LinkButtons. you can use css to give them the look of a real button.

however, it would be hardly elegant, while the design trend actually uses links instead of buttons (look at any popular web application that you like, including this one)

0
source share

All Articles