从GridView中删除记录。在此之前,要求确认,例如“您确定要删除吗?”

5

我希望能够从GridView中删除记录。在此之前,要求确认是否要删除,例如“您确定要删除吗?”

我在GridView中使用了命令字段。

<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />

我在JavaScript中编写了一个函数。
function confirm_Delete()
{
    var r = confirm("Are you sure you want to Remove this Record!");

    if (r == true)
    {
        alert("Record Deleted");
        return true;
    }
    else 
    {
        return false;
    }
}

如何在删除按钮点击时调用此功能。请提供建议!
4个回答

5

你无法使用命令字段实现这一点,必须创建一个模板字段:

<asp:TemplateField>
        <ItemTemplate>
            <asp:LinkButton ID="lbtnDelete" runat="server" CommandName="Delete" Text="Delete" 
             OnClientClick="javascript:return confirm('Are you sure you want to Remove this Record!');">
            </asp:LinkButton>
        </ItemTemplate>
    </asp:TemplateField>

它将与您目前使用的命令字段具有相同的行为。

5

我会像@Muhammad告诉你的那样去做,同时在服务器端删除代码中,我还会注册一个脚本来显示“记录已删除”消息,如下所示;

public void MethodForDeletingARecord()
{
    ScriptManager.RegisterStartupScript(this.Page, base.GetType(), "RecordDeletedMessage", "javascript:alert('Record Deleted');", true);
}

这个人抄袭了你的代码,只是为了给自己投票。我已经举报了他,因为他也对我做了同样的事情。 - Aristos

4
我认为你可以通过命令字段实现这一点。假设它是第一列,在此处找到
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // reference the Delete LinkButton
        LinkButton db = (LinkButton)e.Row.Cells[0].Controls[0];

        db.OnClientClick = "javascript:return confirm('Are you certain you want to delete?');"
    }
}

如果你想要调整它以便与第一列以外的内容一起使用,那么if (e.ColumnIndex == dataGridView.Columns ["clm_Delete"].Index)是我验证删除按钮是否在删除列中被点击的方式。 - clamchoda

3
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        ((LinkButton)e.Row.Cells[0].Controls[0]).Attributes.Add("onclick", "return Conformation();");
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接