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

5
我有一个带有onRowDeleting方法的gridview。我想提示用户是否要删除此项,如果用户点击“OK”、“确认”或类似的选项,则会处理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";
}

这可能会对你有所帮助 http://msdn.microsoft.com/en-us/library/bb428868.aspx - gabsferreira
6个回答

14

你应该使用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

这个JavaScript函数将返回用户单击“确定”或“取消”的结果。如果JavaScript事件处理程序返回false,页面将不会向服务器回传数据。


5

“return confirm(..)” JavaScript 的方法是正确的。

问题在于 ASP.NET 会追加调用 __doPostBack 的 js。

因此,在您的 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) 确认返回True。 5) 语句开头处的return执行,但__doPostBack没有被调用。
解决方案是仅在确认返回false时才返回:
OnClientClick="if(!confirm('Are you sure you want to delete this Plan?')) return;"

如果用户点击“确定”按钮,则确认返回True,然后执行__doPostBack。

这是有用的信息。然而,有时仅仅返回会直接进入处理程序。将函数调整为返回 true 或 false 就可以解决这个问题;OnClientClick="if(!confirm('你确定要删除这个计划吗?')){return false;} else{return true;}" - Houdini Sutherland
优秀的解决方案。 - Mehmet

1

只需调用一个返回布尔值的JavaScript函数,通过"return"来调用,如果返回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();
       }
    }

0

按命令按钮类型获取

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?');";
    }
}

0
另一种方式:
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?');";
                }
            }
        }

0
 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 + "?');";
        }
    }

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