Add a clickable image to a GridView in ASP.Net

27,642

Solution 1

Normally you need to identify which record you want to delete, you can use the CommadArgument property to identify the record's Id:

<asp:TemplateField HeaderStyle-Width="40">
    <ItemTemplate>
        <asp:ImageButton ID="ButtonDelete" runat="server"  
            ImageUrl="~/Imags/delete.png" OnClick="ButtonDelete_Click" ToolTip="Delete"
            CommandArgument='<%#Bind("UserId")%>'/>
    </ItemTemplate>
</asp:TemplateField>

protected void ButtonDelete_Click(object sender, EventArgs e)
{
    ImageButton button = sender as ImageButton;
    DeleteUserById(Convert.ToInt32(button.CommandArgument));
}

Solution 2

<asp:TemplateField>
 <ItemTemplate>
    <asp:ImageButton ID="btnDelete" runat="server"  
        ImageUrl="~/Imags/delete.png" OnClick="btnDelete_Click"
 ToolTip="Delete row" CommandName="Eliminar" CommandArgument='<%#Eval("UserId")%>'/>
 </ItemTemplate>

You can use the CommandArgument to pass the ID value of the selected row and perform the desires results

// fires when the ImageButton gets clicked
protected void GridView1_ItemCommand(object sender, DataGridCommandEventArgs e)
{
  if(e.Commandname ="Eliminar"){
  this.Eliminar(Convert.ToInt32(e.CommandArgument));

}

}

// function to delete the record
 private void Eliminar(int code)
 { 
    //custom code to delete the records
 }
Share:
27,642
user1131661
Author by

user1131661

Updated on July 09, 2022

Comments

  • user1131661
    user1131661 almost 2 years

    I'm trying to add an delete image at the end of each row in a GridView. I want the user to be able to click the image to delete the row.

    So I've used a HyperLinkField to create a link to another page which will delete the record:

    <asp:HyperLinkField DataNavigateUrlFields="ID" 
                            DataNavigateUrlFormatString="RemoveLine.aspx?ID={0}"                             
                            Target="_blank"   />
    

    The HyperLinkField doesn't contain an Image tag so I created a TemplateField with an Image inside.

    <asp:TemplateField>
        <ItemTemplate>
            <asp:Image ID="imageRemove" runat="server" ImageUrl="~/Images/smallcross.gif"  />                                
        </ItemTemplate>                        
    </asp:TemplateField>
    

    However the HyperLinkField and Image appear in different columns and the image has no click event.

    Any way of combining the two?

    I'm using ASP.Net 4.0.

    Thanks in advance