ASP.NET Gridview仅在确认时删除行

本文关键字:确认 删除行 NET Gridview ASP | 更新日期: 2023-09-27 18:21:29

我有一个实现了onRowDeleting方法的gridview。我想用弹出消息提示用户,确认他们是否希望删除此项目。如果用户单击"确定"、"确认"或类似的按钮,那么我希望处理onRowsDeleting并删除记录。但如果用户按下"否",那么我希望取消该方法,并且不删除该记录。

如何做到这一点?

这是我在代码后面的gridviewonRowDeleting方法。

<asp:GridView runat="server" ID="gvShowQuestionnaires" HeaderStyle-CssClass="table_header" CssClass="view" AlternatingRowStyle-CssClass="alt" AlternatingRowStyle-BackColor="#f3f4f8" AutoGenerateColumns="False" 
            DataKeyNames='QuestionnaireID' OnRowDeleting="gvShowQuestionnaires_RowDeleting" OnRowEditing="gvShowQuestionnaires_RowEdit" OnSelectedIndexChanged="gvShowQuestionnaires_SelectedIndexChanged" FooterStyle-CssClass="view_table_footer" > 
    <Columns>
         <asp:BoundField DataField="QuestionnaireID" HeaderText="ID" HeaderStyle-Width="80px" ItemStyle-CssClass="bo"></asp:BoundField>
         <asp:BoundField DataField="QuestionnaireName" HeaderText="Questionnaire Name" />                     
         <asp:ButtonField CommandName="select" ButtonType="Link" Text="view results" />
         <asp:CommandField HeaderText="Options" CausesValidation="true" ShowDeleteButton="True" ShowEditButton="true" EditText="Edit">
         </asp:CommandField>
     </Columns> 
</asp:GridView>
protected void gvShowQuestionnaires_RowDeleting(object sender, GridViewDeleteEventArgs e)
{       
    int questionnaireID = (int)gvShowQuestionnaires.DataKeys[Convert.ToInt32(e.RowIndex)].Value; 
    GetData.DeleteQuestionnaire(questionnaireID);
    gvShowQuestionnaires.DataSource = DT;
    gvShowQuestionnaires.DataBind();
    lblActivity.Visible = true;
    lblActivity.Text = "Your questionnaire has been deleted";
}

ASP.NET Gridview仅在确认时删除行

您应该使用javascript在客户端执行此操作。

因此,您可以处理GridView的RowDataBound事件,将其添加到删除按钮的OnClientClick:

protected void gvShowQuestionnaires_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // reference the Delete LinkButton
        LinkButton db = (LinkButton)e.Row.Cells[3].Controls[0];
        db.OnClientClick = "return confirm('Are you certain you want to delete this questionnaire?');";
    }
}

http://msdn.microsoft.com/en-us/library/bb428868.aspx

这个js函数会返回用户点击了ok还是cancel。如果js事件处理程序返回false,则页面将不会回发到服务器。

"return confirm(..")Javascript走在了正确的轨道上。

问题是ASP.NET会附加js来调用__doPostBack

所以你会在HTML中为删除按钮得到这样的东西:

OnClickClient="return confirm('Are you sure you want to delete this record?');";javascript:__doPostBack(&#39;ctl00$Main$PlansGrid&#39;,&#39;Delete$101&#39;)"

结果是:1) 用户单击"删除"按钮。2) 显示确认对话框。3) 用户单击"确定"按钮。4) Confirm返回True。5) 执行语句开头的return,并且不调用__doPostBack。

解决方案是仅在confirm返回false时返回:

OnClientClick="if(!confirm('Are you sure you want to delete this Plan?')) return;"

如果用户单击"确定",确认返回True,然后执行__doPostBack。

只需通过"return"调用者调用返回布尔值的JavaScript函数,因此如果返回false,则该链接按钮将不起作用。

ASPX-

<asp:LinkButton runat="server" OnClientClick="return DeleteItem();" locationID='<%# DataBinder.Eval (Container.DataItem,"Id").ToString() %>' ID="linkDelete" OnClick="linkDelete_Click" title='<%# "Delete " + DataBinder.Eval (Container.DataItem,"City").ToString() %>' Style="float: left;"><img src="Asset/img/icon/bin.gif" alt="" hspace="3" /></asp:LinkButton>

Javascript

<script type="text/javascript">
    function DeleteItem() {
        if (confirm("Delete this Location?")) {
            return true;
        } else {
            return false;
        }
    }
</script>

服务器端

protected void linkDelete_Click(object sender, EventArgs e)
    {
       int locationID =0;
       int.TryParse(((LinkButton)sender).Attributes["locationID"].ToString(),out locationID);
       if (locationID > 0)
       {
           Location loc = Location.GetById(locationID);
           CurrentDataContext.CurrentContext.DeleteObject(loc);
           CurrentDataContext.CurrentContext.SaveChanges();
           bindGv();
       }
    }

另一种方式:

if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // loop all data rows
            foreach (DataControlFieldCell cell in e.Row.Cells)
            {
                // check all cells in one row
                foreach (Control control in cell.Controls)
                {
                    // Must use LinkButton here instead of ImageButton
                    // if you are having Links (not images) as the command button.
                    LinkButton button = control as LinkButton;
                    if (button != null && button.CommandName == "Delete")
                        // Add delete confirmation
                        button.OnClientClick = "return confirm('Are you sure " +
                               "you want to delete this record?');";
                }
            }
        }
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        string id = e.Row.Cells[2].Text;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton db = (LinkButton)e.Row.Cells[6].Controls[0];
            db.OnClientClick = "return confirm('Are you want to delete this Work Description : " + id + "?');";
        }
    }

通过命令按钮类型获取

protected void gvShowQuestionnaires_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // handle the Command Column Index
        var commandColumnIndex = GvOperators.Columns
              .OfType<DataControlField>()
              .Select((x, i) => new { Index = i, Column = x })
              .FirstOrDefault(x => x.Column is CommandField)
              .Index;
        var commandButtons = e.Row.Cells[commandColumnIndex].Controls.OfType<LinkButton>();
        // reference the Delete LinkButton
        var db = commandButtons.FirstOrDefault(x => x.CommandName == "Delete");
        if(db!=null)       
          db.OnClientClick = "return confirm('Are you certain you want to delete this questionnaire?');";
    }
}