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

HGo*_*mez 3 c# asp.net confirm gridview

我有一个实现gridviewonRowDeleting方法.我想用弹出消息提示用户确认是否要删除此项目.如果用户单击"确定","确认"或类似的东西,那么我希望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";
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 11

你应该使用javascript在客户端执行此操作.

因此,您可以处理GridView的RowDataBound事件以将其添加到Delete-Button 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?');";
    }
}
Run Code Online (Sandbox Code Playgroud)

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

这JS-函数将返回用户是否点击okcancel.如果js-eventhandler返回false,则页面不会回发到服务器.


Coo*_*eze 5

“返回确认(..”)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;)"
Run Code Online (Sandbox Code Playgroud)

发生的情况是: 1) 用户单击“删除”按钮。2) 显示确认对话框。3) 用户单击“确定”按钮。4) 确认返回True。5) 在语句执行开始时返回,并且不调用 __doPostBack。

解决办法是只有当confirm返回false时才返回:

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

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