Search code examples
javascriptasp.netconfirmation

GridView TemplateField Confirmation Box


I am using a gridview with a hyperlink inside to do a postback in order to delete some data, this is my code

<asp:GridView ID="downloadFilesTable" runat="server" BorderStyle="Solid"
    AutoGenerateColumns="False" DataKeyNames="DOCID" 
    DataSourceID="SqlDataSource1" 
    OnSelectedIndexChanged="downloadFilesTable_SelectedIndexChanged">
    <Columns>
        <asp:BoundField DataField="DOCID" HeaderText="DOCID" InsertVisible="False" ReadOnly="True" SortExpression="DOCID" />
        <asp:BoundField DataField="FILENAME" HeaderText="FILENAME" SortExpression="FILENAME" />
        <asp:BoundField DataField="EXTENSION" HeaderText="EXTENSION" SortExpression="EXTENSION" />
        <asp:HyperLinkField  
            DataNavigateUrlFields="DOCID"
            DataNavigateUrlFormatString="DownloadFile.aspx?id={0}"
            HeaderText="File" 
            Text="Open" />
        <asp:TemplateField HeaderText="File">
            <ItemTemplate>
                <asp:HyperLink runat="server" 
                    NavigateUrl='<%# "~/ViewDocument.aspx?table="
                        + Request.QueryString["table"].ToString() 
                        + "&id=" + Request.QueryString["id"].ToString() 
                        + "&docid=" + Request.QueryString["docid"].ToString() 
                        + "&remove=" + Server.UrlEncode(Eval("docid").ToString())%>' 
                    datanavigateurlfields="docid" 
                    HeaderText="File" 
                    Text="Remove" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

User will click on the ItemTemplate hyperlink to remove the data, but the problem is, when i want to remove the data, i want a confirmation box , if the user clicks yes i will delete the data, this is a gridview as i dont think i have access to the onclick function, Any Clue? (for ex. Doing in server side?) Every help is much appreciated, thanks in advance!


Solution

  • Every time the grid loads, it loads one row at a time and has an event you can use called RowDataBound.

    Change your control to a LinkButton because it has an OnClientClick event.

    protected void gvw_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow) 
        {
            // reference the Delete button. (i think it's cell 4.)
            LinkButton lbtn = (LinkButton)e.Row.Cells[4].Controls[0]; 
    
            lbtn.OnClientClick = "return confirm('Are you certain you want to delete?');"
        }
    }