How to make javascript confirm box from asp:buttonfield?
-
11-12-2019 - |
Question
I'm having a hard time getting a javascript confirm box from asp:buttonfield:
This is the original code of the Gridview, however buttonfield does not seem to accept "onClientClick"
<asp:GridView ID="gvNavios" runat="server" onrowcommand="gvNavios_RowCommand">
<Columns>
<asp:ButtonField runat="server" ButtonType="Button" Text="delete" CommandName="Eliminar" />
</Columns>
</asp:GridView>
So I tried asp:Linkbutton instead:
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="eliminar" CommandName="delete" runat="server" Text="delete"/>
</ItemTemplate>
</asp:TemplateField>
However this way I cannot get which row was clicked as e.commandargument is not filled
The C# code-behind:
protected void gvNavios_RowCommand(object sender, GridViewCommandEventArgs e)
{
string currentCommand = e.CommandName;
int currentRowIndex = Int32.Parse(e.CommandArgument.ToString());
string imo = gvNavios.Rows[currentRowIndex].Cells[3].Text;
if (currentCommand.Equals("delete"))
{
eliminarNavio(imo);
Response.Redirect(Request.RawUrl);
}
}
I appreciate one of the following: Insert javascript in asp:button, or get Row number from linkbutton.
Solution
You need to add the CommandArgument to the LinkButton and provide some index (the object ID will be the best).
<asp:LinkButton ID="eliminar" CommandArgument='<%# Eval("ID") %>' CommandName="delete" runat="server" Text="delete"/>
OTHER TIPS
Porque no usas un templatefield ?, creo es mas facil
why dont u use a templatefield ?¿
inside the RowDataBound :
First create a templatefield, then inside the templatefield insert an imageButton, Call it img_borrar(commandName).
Then in the rowcommand, find it, set the index (CommandArgument), set some style, and the java comfirmation:
If e.Row.RowType = DataControlRowType.DataRow Then
Dim boton_borrar As ImageButton = CType(e.Row.Cells(1).FindControl("img_borrar"), ImageButton)
boton_borrar .CommandArgument = e.Row.RowIndex.ToString
boton_borrar .Style("cursor") = "hand"
boton_borrar .Attributes.Add("onClick", "return window.confirm(' ¿Desea borrar este registro? ');")
End If