Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use images instead of text for AutoGenerateEditButton in ASP.Net GridView

I'm using AutoGenerateEditButton and the Delete and Select ones as well.

I'd like to use images instead of text for the links.

How do I do this?

I don't want to manually create the command columns, since the AutoGenerate properties are used throughout a large project I'm working on.

like image 373
Brad Bruce Avatar asked Jan 21 '23 18:01

Brad Bruce


1 Answers

The easiest way to do this is to handle it all yourself. Here is a quick example using an ImageButton to replace the edit command button:

<asp:GridView ID="yourGrid" runat="server" OnRowEditing="yourGrid_RowEditing">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:ImageButton ID="yourEditButton" runat="server"
                    CommandName="Edit" ImageUrl="edit.jpg" />
            </ItemTemplate>
            <EditItemTemplate>
                <!-- your edit controls here -->
            </EditItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Now for the code behind:

protected void yourGrid_RowEditing(object sender, GridViewEditEventArgs e)
{
    // You could just do yourGrid and ignore casting the sender but this 
    // makes the code generic for reuse.
    GridView grid = (GridView)sender;   
    grid.EditIndex = e.NewEditIndex;
    BindData(); // need to rebind once the edit index is set.
}

This pretty much replaces the auto generated edit button with an ImageButton. By setting the CommandName to edit, it will trigger the exact same events as the auto generated edit button. This would also apply to delete, update, etc...

like image 77
Kelsey Avatar answered Jan 25 '23 14:01

Kelsey