GridView 增加删除确认提示(button类控件应用)

我从网上找的 GridView 增加删除确认提示

1、增加一个列。当然也可以启用GridView里的删除列  <asp:CommandField ShowDeleteButton="true" /> 
2、在行的数据绑定事件里增加以下代码:

    protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)

    {

       if (e.Row.RowType ==DataControlRowType.DataRow)
        {
            if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
            {
                ((LinkButton)e.Row.Cells[0].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:\"" + e.Row.Cells[1].Text + "\"吗?')");
            }
        }
    }

 

测试通过!

这里注意的一点是 按钮类型必须是Link,不能是Button,否则每次点“取消”的话它也执行。这个问题我经常碰到。如果button的类型,经常连ItemCommand(2003)里的命令都无法获取。

 

我自己的

aspx文件

------

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvMearList" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvMearList_RowDataBound" OnRowDeleting="gvMearList_RowDeleting" OnRowUpdating="gvMearList_RowUpdating">
            <Columns>
                <asp:BoundField ConvertEmptyStringToNull="False" DataField="PKID" Visible="False" />
                <asp:CommandField ButtonType="Button" ShowDeleteButton="True" ShowEditButton="True" />
                <asp:BoundField ConvertEmptyStringToNull="False" DataField="PKID" />
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

------

cs 文件

 protected void gvMearList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ((Button)e.Row.Cells[1].Controls[2]).Attributes.Add("
onclick", "if(confirm('确定删除?')){}else{return false;}");
        }

    }

-------

如果是这么写的话

Attributes.Add("onclick", "javascript:return confirm('xxxx');");

生成的是:

onclick="javascript:return confirm('确定删除?');javascript:__doPostBack('gvList','Delete$0')";

无论你点什么都不会执行删除后面的功能;因为return 了

如果是这么写的话

Attributes.Add("onclick", "confirm('xxxx');");

生成的是:

onclick="confirm('确定删除?');javascript:__doPostBack('gvList','Delete$0')";

你怎么点都执行后面的__doPostBack

所以稍加改改就可以了

if(confirm('确定删除?')){}else{return false;}

很简单是吧!

原文地址:https://www.cnblogs.com/wenming205/p/1244019.html