本文介绍了使用jQuery对话框删除GridView行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一切正常,除了删除行时不发生回发.我在OnRowDeleting和OnRowDataBound里面放了一个调试器中断唯一的区别是您没有Ajax更新面板和脚本管理器.下面是Gridview的图像.当我单击确定"按钮时,什么也没发生.

Everything is working fine except that postback does not occur when I delete the row. I put a debugger break inside the OnRowDeleting and OnRowDataBoundThe only difference is that you don't have Ajax update panel and script Manger. Below is the image of the Gridview. Nothing happens When I click the ok button.

下面是我在新页面上的代码:

Below is my code on fresh page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="SidePanelGridViewTest.WebForm3" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div>

            <asp:SqlDataSource ID="SqlDataSource1" runat="server"
                    ConnectionString="<%$ ConnectionStrings:IdDatabase %>"
                    SelectCommand="SELECT TOP 5 ProductID, ProductName FROM [TableA]">
</asp:SqlDataSource>
            <asp:ScriptManager ID="scMan" runat="server"></asp:ScriptManager>
 <asp:UpdatePanel ID="updPnl" runat="server" UpdateMode="Always">
            <ContentTemplate>

<asp:GridView ID="grdShoppingCart" runat="server" AutoGenerateColumns="False"
    DataKeyNames="ProductID" DataSourceID="SqlDataSource1" OnRowDeleting="OnRowDeleting"  OnRowDataBound="OnRowDataBound" >
    <Columns>
        <asp:BoundField DataField="ProductID" HeaderText="ProductID"
            InsertVisible="False" ReadOnly="True"  />
        <asp:BoundField DataField="ProductName" HeaderText="ProductName"
             />
         <asp:TemplateField ShowHeader="False" HeaderStyle-HorizontalAlign="center" ItemStyle-HorizontalAlign="center" ItemStyle-Width="150px" ControlStyle-CssClass="ss-row" >
                        <ItemTemplate>
                              <asp:ImageButton ID="imgbtnDelete" runat="server" ImageUrl="~/Images/delete1.png" ToolTip="Click To Delete" AlternateText="Click To delete" OnClientClick="myclick(this.id);return false;"/>
                              <asp:Button ID="MyDelete" runat="server" Text="del" CommandName="MyDelete" CommandArgument='<%# Eval("ProductID") %>' style="display:none"/>

                       </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    </asp:GridView>
 </ContentTemplate>
     </asp:UpdatePanel>

        </div>
        <div id ="mydialog" style="display:none" runat="server">
              <h2>Do you really want to delete?</h2>
        </div>
        <script>
    function myclick(mycontrolid) {
        var mydiv = $('#mydialog');

        mydiv.dialog({
            autoOpen: false, modal: true, title: 'Delete?', width: '25%',
            position: { my: 'top', at: 'top+150' },
            buttons: {
                'ok': function () {
                    vbtns = '#' + mycontrolid.replace('imgbtnDelete', 'MyDelete');
                    $(vbtns).click();
                },
                'cancel': function () {
                    mydiv.dialog('close');
                }
            }
        });
        mydiv.dialog('open');
    }

</script>



    </form>
</body>
</html>

下面是gridview的图像:

below is the image of the gridview:

当我点击确定"时,在删除按钮上弹出.回发不会发生.我在OnRowDeleting和OnRowDataBound上都有一个调试器中断.当我开始运行代码时,调试器会在OnRowDataBound上中断,但是在弹出窗口上单击确定"按钮不会导致回发.

when I click on "Ok" button in the delete pop up. postback does not occur. I have a debugger break on both OnRowDeleting and OnRowDataBound. when I start running the code, debugger breaks on OnRowDataBound, but clicking on "OK' button on the pop up does not cause postback.

下面是背后的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SidePanelGridViewTest
{
    public partial class WebForm3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int index = Convert.ToInt32(e.RowIndex);


        }

        protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            string x = "Test";

        }
    }
}

推荐答案

好,我要咬一口.

原因是我经历了这个,而工作的例子是恐怖-遭受苦难!

And the REASON is that I went through this, and the working examples are HORRID – BEYOND suffering!!

所以,让我们开始吧.

首先,与JavaScript(js)警报"或确认"不同吗?

First up, unlike JavaScript (js) "alert" or "confirm"?

大多数网络内容,包括jQuery.UI都不会停止,也不会阻止代码.

Most web stuff and including jQuery.UI does NOT halt, nor does it block code.

这意味着我们的图像"按钮单击"不能返回true或false,因为我们的对话框不会等待.因此,我们必须获取对话框的结果,然后运行删除按钮的代码.

This means our "image" button "on click" can’t be used to return true or false, since our dialog does NOT wait. We thus have to get the results of the dialog AND THEN run that delete button code.

鉴于上面?

然后最简单的方法是在该网格中放置一个隐藏的删除按钮.然后,我们为我们的jQuery.UI单击"该删除按钮.

Then most simple is placing a hidden delete button into that grid. We then have our jQuery.UI "click" that delete button for us.

jQuery.ui希望在jQuery选择器上操作".这意味着$(请选择这个东西")

jQuery.ui expects to "operate" on a jQuery selector. That means $("please select this thing")

通常是某些控件或按钮,但是对于对话框,通常是您在页面上放置的div(并将其隐藏---仅供参考:请注意我们如何隐藏jQuery.UI对话框"div"和ALSO)我们如何使用style ="display:none")隐藏删除按钮.

Often that is some control or button, but for dialogs, most often that is a div you place on the page (and hide it --- FYI: note how we hid the jQuery.UI dialog "div" and ALSO how we hide the delete button with style="display:none").

因此,让我们添加删除按钮-在图像按钮的正下方(顺便说一下,您可以在此处使用asp.net按钮-您不仅限于图像按钮).

So, let’s add our delete button – right below the image button (and by the way, you can use an asp.net button here – you’re not limited to an image button).

因此,图像按钮的唯一工作是现在调用我们的jquery对话框-但它无法运行我们的服务器端删除代码.

So, ONLY job of image button is to NOW call our jquery dialog – but it CAN NOT run our server side delete code.

因此,我们添加该删除按钮.

So, let’s add that delete button.

我们将删除内容从图像按钮移至该按钮.

We MOVE the delete stuff to this button FROM the image button.

所以,我们现在有这个:

So, we have this now:

<asp:TemplateField>
    <ItemTemplate>
        <asp:ImageButton ID="imgbtnDelete" runat="server"
           ImageUrl="~/Images/delete1.png" ToolTip="Click To Delete"
           AlternateText="Click To delete"
           OnClientClick="myclick(this.id);return false;"
        />

    <asp:Button ID="MyDelete" runat="server" Text="del"
           CommandName="MyDelete"
           CommandArgument='<%# Eval("CartID") %>'
           style="display:none"/>

  </ItemTemplate>
</asp:TemplateField>

因此,我们将返回false,并且不会运行该图像按钮服务器端的点击或进行回发.

So, we WILL RETURN false and NOT have that image button server side click run, or do a post-back.

因此,更改图片按钮(以调用我们的简单js函数.

So, change the image button (to call our simple js function.

请注意,我们如何将功能和信息移至隐藏的我的删除"按钮.

NOTE HOW we moved the features and information to our hidden "my delete" button.

以供参考:请记住,在网格视图中,commandName在这里具有SPECIAL含义.因此,如果我们同时填写CommandName和CommandArgument,则将触发GridView行命令"事件!!!

As FYI:Remember in a grid view, the commandName has SPECIAL meaning here. So, if we fill out both CommandName and CommandArgument, then the GridView "row command" event will fire!!!

看起来您现在仍在执行此操作(使用行命令).

And it looks like you doing that now anyway (using row command).

这是脚本+标记:

</asp:GridView>   ---- end of your gridview

<div id ="mydialog" style="display:none" runat="server">
     <h2>Do you really want to delete?</h2>
</div>

<script>
   function myclick(mycontrolid) {
      var mydiv = $('#mydialog');

      mydiv.dialog({
         autoOpen: false, modal: true, title: 'Delete?', width: '25%',
         position: { my: 'top', at: 'top+150' },
          buttons: {
             'ok': function () {
              vbtns = '#' + mycontrolid.replace('imgbtnDelete', 'MyDelete');
              $(vbtns).click();
              },
              'cancel': function () {
                        mydiv.dialog('close');
               }
          }
       });
       mydiv.dialog('open');
    }

</script>

这就是您在这里所需要的(删除您拥有的其他初始化" js垃圾).

And that is ALL you need here (remove that other "initialize" js junk you have).

结果应如下所示:

因此,上面的代码最少能起作用.有十二种不同的方法可以做到这一点.但是我认为上面很简单.

So above is about the least amount of code for this to work. There are a dozen different ways to do this. But above is I think quite simple.

因此,我已经提出了上述建议,因为我们在js中对删除按钮进行了"click()"操作,因此,按行行事件中的现有代码存根可以保留在原处,因为您现在无疑拥有它了. (因此,此处建议的解决方案考虑了您现有的设置).

So, I have suggested the above since we in js do a "click()" of our delete button, and thus your existing code stub in the on-command row event can remain in place as you no doubt have it now. (So the suggested solution here takes into account your existing setup).

最后的好措施是什么?我们的删除命令将如下所示:

And for final good measure? our delete command will look like this:

Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GridView1.RowCommand

    If e.CommandName = "MyDelete" Then

        Using cmdSQL As New SqlCommand("DELETE FROM tblHotels where ID = " & e.CommandArgument,
                    New SqlConnection(My.Settings.Test3))
            cmdSQL.Connection.Open()
            cmdSQL.ExecuteNonQuery()
        End Using

        LoadGrid()    ' re-load the grid
    End If
End Sub

请注意,您可能确实调用了代码以在第一篇文章中加载网格(而不是其他文章的背面),但是如上所示,删除时,您需要重新加载网格,因为它确实具有视图状态,并且无需重新加载网格视图,该删除的行仍将保留在视图中.

Note that you probably did call your code to load the grid up on first post (and NOT additonal post backs, but as above shows, WHEN you delete, you need to re-load the grid, since it does have a view state, and without a re-load of the grid view, then that deleted row WILL remain in view.

----------------

----------------

发布的代码似乎不包含jQuery.UI.

It looks like the posted code DOES NOT include jQuery.UI.

您既需要jQuery,也需要jQuery.UI.他们是两个独立的自由.

You need BOTH jQuery, and ALSO need jQuery.UI. They are two separate libriies.

此外,jQuery.UI还需要一个样式表,并且必须将其放置在jQuery.UI引用之前.

Also, jQuery.UI ALSO needs a style sheet, and it MUST be placed before the jQuery.UI referance.

屏幕截图和有效的测试代码,从"body"开始asp.net Web表单页面中的标签如下所示:

The screen shots and working test code, starting at the "body" tag in the asp.net web form page looks like this:

<body>
<form id="form1" runat="server">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID">
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
                <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
                <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
                <asp:BoundField DataField="HotelName" HeaderText="HotelName" SortExpression="HotelName" />
                <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Button ID="Button2" runat="server" Text="Button"
                            OnClientClick="myclick(this.id);return false;"
                           />

                        <asp:Button ID="MyDelete" runat="server" Text="Button3"
                            CommandName="MyDelete"
                            CommandArgument='<%# Eval("ID") %>'
                            style="display:none"/>

                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

        <div id ="mydialog" style="display:none" runat="server">
            <h2>Do you really want to delete?</h2>
        </div>

    <script>

        function myclick(mycontrolid) {

            var mydiv = $('#mydialog');

            mydiv.dialog({
                autoOpen: false, modal: true, title: 'Delete?', width: '25%',
                position: { my: 'top', at: 'top+150' },
                buttons: {
                    'ok': function () {
                        vbtns = '#' + mycontrolid.replace('Button2', 'MyDelete');
                        $(vbtns).click();
                    },
                    'cancel': function () {
                        mydiv.dialog('close');
                    }
                }
            });
            mydiv.dialog('open');
        }

    </script>
</form>
</body>

请注意,我确实将jQuery和jQuery.UI脚本引用放置在form标签的内部,但通常用户会将引用放置在"head"标签的内部.标签.

Note I did place the jQuery and the jQuery.UI script references right inside of the form tag, but often users will place the references inside of the "head" tag.

但为了便于发布-我在表单"表单的内部添加了jQuery和广告jQuery.UI引用.标签.

but for ease of posting - I have included the jQuery, ad jQuery.UI references inside of the "form" tags.

这篇关于使用jQuery对话框删除GridView行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 19:16