CommandField中的删除确认消息?

4
我正在尝试在 GridView 中单击 删除 按钮时获得 确认 消息。如果我 确认,则只有该行将从 GridView 中删除。
*.ASPX
<Columns>

    <asp:CommandField ButtonType="Button" ShowDeleteButton="true" />

</Columns>

*.ASPX.CS

protected void grdPersTable_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Button buttonCommandField = e.Row.Cells[0].Controls[0] as Button;
        buttonCommandField.Attributes["onClick"] = 
               string.Format("return confirm('Are you want delete ')");
    }
}

protected void grdPersTable_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    Label lbl0 = (Label)grdPersTable.Rows[e.RowIndex].FindControl("lblId");
    txtId.Text = lbl0.Text;
    obj.DeleteV(Convert.ToInt32(txtId.Text));
    grdPersTable.DataSource = obj.GetTableValues();
    grdPersTable.DataBind();        
    lblMessage.Text = "Deleted successfully !";
}
5个回答

9
我得到了朋友的答案。
<asp:TemplateField>
      <ItemTemplate>
            <asp:Button ID="deletebtn" runat="server" CommandName="Delete" 
             Text="Delete" OnClientClick="return confirm('Are you sure?');" />
      </ItemTemplate>
</asp:TemplateField>

我把 CommandField 改成了 TemplateField 谢谢!

如果您正在使用SQL,且在DataSource中调用了删除SQL语句,那么您是否仍然能够使用DeleteCommand功能呢? - Zeek2

2
将rowdatabound事件更改如下。
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        ((Button)e.Row.Cells[0].Controls[0]).OnClientClick = "return confirm('Are you sure you want to delete?');"; 
    }
}

1
我使用了上面的代码,但是出现了错误:“无法将类型为'System.Web.UI.LiteralControl'的对象强制转换为类型'System.Web.UI.WebControls.Button'”。 - kasim
1
使用此代码 ((LinkButton)e.Row.Cells[0].Controls[0]).OnClientClick = "return confirm('您确定要删除吗?');"; - Charles Xavier

1

在onclientclick事件上调用JavaScript函数并请求确认。如果返回true,则可以调用服务器端代码进行删除。

以下是解释的代码

<asp:LinkButton ID="lbDelete" runat="server" OnClick="lbDelete_Click" OnClientClick="return fnConfirm();"> Delete</asp:LinkButton>

以下是JavaScript函数:

<script type="text/javascript">
function fnConfirm() {
    if (confirm("The item will be deleted. Are you sure want to continue?") == true)
        return true;
    else
        return false;
}
</script>

您可以在以下链接中查看详细的文章和源代码。

http://www.dotnetpickles.com/2013/03/how-to-show-confirm-message-while.html

谢谢


0
<asp:TemplateField HeaderText="DELETE" ShowHeader="False">
                        <ItemTemplate>
                        <span onclick="return confirm('Are you sure to Delete?')">
                            <asp:Button ID="Button1" runat="server" CausesValidation="False"
                                CommandName="Delete" Text="Delete" />
                        </ItemTemplate>
</asp:TemplateField>

0

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