GridView RowDeleting event fires twice !

Rate It (2)

Last post 12-06-2009 11:06 PM by Marcelo Santos. 28 replies.

Sort Posts:

  • GridView RowDeleting event fires twice !

    06-25-2006, 7:25 PM
    • Member
      240 point Member
    • Brad_M
    • Member since 07-08-2002, 12:16 AM
    • Posts 60

    I'm facing some annoying GridView behavior where it fires the RowDeleting event twice.

    I'm doing the very normal (logical) steps for deleting a row from a GridView. Here is what I'm doing:

    1- my test Page_Load  method

    protected void Page_Load(object sender, EventArgs e)
    {
    
    	GridView1.DataSource = GetDataTable();
    	GridView.DataBind();
    }
    	// Note: GetDataTable() returns a non-null DataTable object.
    	// Also the DataTable has more than 1 row
    	// (i.e. everything is fine with the datatable)
    
    


    2- the GridView has a Delete Command Field.

    3- on tracing I've noticed my RowDeleting event gets fired twice! (also I used a static counter to see how many times the event gets fired when clicking on the GridView delete button, which was also confirmed it that it's counting 2 per each click).

    Am I doing something wrong? please help

     

  • Re: GridView RowDeleting event fires twice !

    06-26-2006, 6:22 AM
    • Member
      240 point Member
    • Brad_M
    • Member since 07-08-2002, 12:16 AM
    • Posts 60
    ok, just in case anyone else is facing events getting triggered twice (for any reason), and getting the infamous "Deleted row information cannot be accessed through the row." exception, I wrote a method that prevents the duplication (unorthodox but it works).

    private bool Ok2Delete(int bypassCount)
    {
            Session["delCount"] = Session["delCount"] == null ? 0 : Session["delCount"];
            return !((int)(Session["delCount"] = (((int)Session["delCount"]) + 1) % bypassCount) == 0);
    
    }
    


    just call it at the beginning of your RowDeleting event handling method. Example:
    if (!Ok2Delete(2)) return; // parameter of 2 if event is firing twice
                                    // 3 if trice, etc...
    


    However, now that the event triggering twice is solve. But the funny part is (for me) the event turned out to be inconsistance in its behaviour (i.e. fires randomly either twice or one time).

    And if someone else also facing similiar inconsistance behaviour, I'd advice to do like what I'll hopefully do; which is letting the user select the rows and clicks on a button (outside the grid) to delete them instead of embeded delete button within each row.
  • Re: GridView RowDeleting event fires twice !

    06-26-2006, 2:50 PM
    • Member
      240 point Member
    • Brad_M
    • Member since 07-08-2002, 12:16 AM
    • Posts 60

    finally I found a proper solution for it. The problem seems a known ASP.NET issue.

    Anyway, I wrote this method that needs to be called at the begninning of the event handling method:

     

        private bool Ok2Delete(int ri) // ri is the record index to be deleted
        {
            if (Session["ri"] == null ||
                (!((ri == ((int)Session["ri"])) &&
                (DateTime.Now.Subtract((DateTime)Session["ri_time_stamp"]).Seconds < 2))))
            {
                Session["ri"] = ri;
                Session["ri_time_stamp"] = DateTime.Now;
                return true;
            }
            return false;
        }
    

    The above method should work even if the behavior of the event is inconsistent (i.e. gets triggered once / twice / trice / n-times)

    Example on how to use it:

     

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            if (!Ok2Delete(e.RowIndex)) return;    
    
            // your logic goes here and the above IF statement 
            // will hopefully guarantee your code to run once.
        }
    

    Hope this will help others that might be facing the same issue.
  • Re: GridView RowDeleting event fires twice !

    07-06-2006, 4:06 PM
    • Member
      5 point Member
    • LouG
    • Member since 07-06-2006, 8:01 PM
    • Posts 1

    I just had the same problem. My solution turned out to be very easy...

    Remove

    AutoEventWireup="true"

    in the Page directives from both the aspx form AND the Master page. I had to remove directive from both to effect the solution.

  • Re: GridView RowDeleting event fires twice !

    08-02-2006, 3:51 AM
    • Member
      25 point Member
    • dvl_vn
    • Member since 08-02-2006, 7:48 AM
    • Posts 5
    Hi
    I'm having this problem too. I will try your solutions. Thanks very much !

  • Re: GridView RowDeleting event fires twice !

    08-03-2006, 4:54 PM
    • Member
      240 point Member
    • Brad_M
    • Member since 07-08-2002, 12:16 AM
    • Posts 60

    I gave up on all the solutions I came up with once I realized that onload() event also gets fired twice.

    And the worst part is when onload gets fired twice, the Page.IsPostBack sometimes returns false when it should return true, which automatically mess up all your initialization code.

    Anyway, I finally understood the problem properly, it turns out there is a bug in the gridview that only happens if you use a command field of type image in one of your gridview columns.

    You can avoid this error if you use a button type command field (instead of image).

    Or in case you have to have an image to represent the delete button, you should completely ignore using the command field and use a template field instead.

    Here is how a delete button tag should look like in your .aspx file when using a template field:

    <asp:TemplateField>

    <ItemStyle HorizontalAlign="Right" Width="10%"/>

    <ItemTemplate>

    <asp:ImageButton runat="server" id="btnDelete" CommandName="cDelete" ImageUrl="../resources/images/delete1.gif"

    CommandArgument='<%# Eval("item_id") %>' OnCommand="OnDelete" />

    </ItemTemplate>

    </asp:TemplateField>

     

    Note: the example above shows how you can pass a value of another column on the same row that you wish to delete (ex: item_id is a field of another column in the same row) to your event handler that can help you delete a record from the database.

    You can also return the row number of the gridview in which you wish to delete by using DataBinder.Eval(Container,"RowIndex") instead of Eval(“your_column_name”)

    And here is the code behind for handling the event “OnDelete”:

    protected void OnDelete(object sender, CommandEventArgs e)

        {

            if (e.CommandName.Equals("cDelete"))

            {

                try

                {

                    string item_id = e.CommandArgument.ToString();

                      // your code to delete the item record from

    // your database using the index item_id

     

                }

                catch (Exception) { }

            }

        }

     

  • Re: GridView RowDeleting event fires twice !

    03-19-2007, 5:24 AM
    • Member
      14 point Member
    • laoujin
    • Member since 10-17-2006, 12:20 PM
    • Posts 4
    I "translated" Brad_M's to VB.NET in case anyone needs it: Private Function Ok2Delete(ByVal pRow As String) As Boolean If Session("RowIndex") Is Nothing OrElse _ (CInt(Session("Rowindex")) = pRow AndAlso DateTime.Now.Subtract(CDate(Session("RowIndexTimeStamp"))).Seconds
  • Re: GridView RowDeleting event fires twice !

    03-19-2007, 5:29 AM
    • Member
      14 point Member
    • laoujin
    • Member since 10-17-2006, 12:20 PM
    • Posts 4

    I "translated" Brad_M's to VB.NET in case anyone needs it:

    	Private Function Ok2Delete(ByVal pRow As String) As Boolean
    		If Session("RowIndex") Is Nothing OrElse _
    		 (CInt(Session("Rowindex")) = pRow AndAlso DateTime.Now.Subtract(CDate(Session("RowIndexTimeStamp"))).Seconds < 2) Then
    
    			Session("RowIndex") = pRow
    			Session("RowIndexTimeStamp") = DateTime.Now
    			Return True
    		End If
    		Return False
    	End Function
     

    And the function call:
     

     

     Protected Sub grd_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grd.RowCommand
      If Not Ok2Delete(e.CommandArgument.ToString()) Then Return
    
    
          End Sub
     

    I'm working with a String instead of an integer here because I'm handling the RowCommand event and not RowDeleting.

     Apparently the forum isn't very compatible with Opera. But this should work now...

  • Re: GridView RowDeleting event fires twice !

    04-12-2007, 8:12 AM
    • Member
      19 point Member
    • itsdanny
    • Member since 07-01-2005, 10:03 AM
    • UK
    • Posts 17

    For what it's worth my solution/dirty hack

    ' Declare a global boolean

    Public exitSub As Boolean = False

    Sub DothisOnce(blah, blah)
    If exitSub = True Then
        Exit Sub
    End If
    ' Do some coding/DB work or something

    '  code has ran so set boolean to true
    ExitSub = True
    End Sub

    NB the sub still 'fires' twice still but exits as soon as the if statement is entered on the 2nd iteration. What a strange bug.

    HTHIndifferent 

    itsdanny 

    DYOR
  • Re: GridView RowDeleting event fires twice !

    04-23-2007, 1:21 AM
    • Member
      48 point Member
    • dstorfer
    • Member since 04-25-2003, 11:40 AM
    • Buffalo, NY
    • Posts 12

    Here's a link to some information regarding Microsoft's awareness of this bug and a fairly good workaround that doesn't involve hacky flags:

    http://www.issociate.de/board/post/285047/help_please_on_GridView_commands_+_AutoEventWireUp

    Thanks for reporting the issue. This is a known issue and we are
    investigating fixing this in the next service pack. For the time being
    you could use the following work around. One obvious workaround is to
    change the button type to a regular button or a link button. If you need
    an ImageButton, then you can put an ImageButton in a TemplateField. You
    may need to handle the Command event on the ImageButton and call
    DeleteRow, passing the RowIndex as the CommandArgument, like this:

     

    <asp:GridView ID="GridView1" runat="server"> 
    <Columns> 
    <asp:TemplateField> 
    <ItemTemplate> 
    <asp:ImageButton runat=server id="ImageButton1" CommandName="Delete"
    ImageUrl="..." CommandArgument='<%# DataBinder.Eval(Container,
    "RowIndex") %>' OnCommand="ImageButton1_Command" /> 
    </ItemTemplate> 
    </asp:TemplateField> 
    </Columns> 
    </asp:GridView> 
    
    protected void ImageButton1_Command(object sender, CommandEventArgs e) {
    GridView1.DeleteRow(Int32.Parse(e.CommandArgument.ToString() )); 
    } 
    
    
     

  • Re: GridView RowDeleting event fires twice !

    05-03-2007, 2:23 AM
    • Member
      11 point Member
    • svidito
    • Member since 01-24-2006, 9:18 AM
    • Posts 4

    Right on! Thanks everyone for all your posts on this matter. I was also using an image button for the delete command. I was completely cluesless on why the event was firing twice and the page was reloading and deleting two items instead of just the one selected.

     It was helpful enough that I signed up just to post and thank everyone for the educated tips!

  • Re: GridView RowDeleting event fires twice !

    05-03-2007, 2:23 AM
    • Member
      11 point Member
    • svidito
    • Member since 01-24-2006, 9:18 AM
    • Posts 4

    Right on! Thanks everyone for all your posts on this matter. I was also using an image button for the delete command. I was completely cluesless on why the event was firing twice and the page was reloading and deleting two items instead of just the one selected.

     It was helpful enough that I signed up just to post and thank everyone for the educated tips!

    Scott Vidito

    StrongerNutrition.com

  • Re: GridView RowDeleting event fires twice !

    05-03-2007, 2:25 AM
    • Member
      11 point Member
    • svidito
    • Member since 01-24-2006, 9:18 AM
    • Posts 4
    Also my website, is StrongerNutrition.com. If anyone gets a chance, let me know what you think and offer any constructive critism that you can so I can improve the site!
  • Re: GridView RowDeleting event fires twice ! (My Solution)

    06-19-2007, 6:27 PM
    • Member
      2 point Member
    • Mimix
    • Member since 06-19-2007, 10:08 PM
    • Posts 1

    I have a solution to this issue that is probably the cleanest I have seen.  I will allow you to make the fewest changes to your code and continue using the RowDeleting and RowDeleted events for the  GridView.
    Currently when you build a command field for a delete button it will look something like this.

     <asp:CommandField ButtonType="Image" DeleteImageUrl="images/delete.gif" ShowDeleteButton="true"  />

    By Changing the ButtonType to "Link" and modifying the DeleteText you will have the same delete image that works exactly like the Image Button Type but without the double firing event.  Here is the modified code.

    <asp:CommandField ButtonType="Link" DeleteText="<img src='images/delete.gif' alt='Delete this' border='0' />" ShowDeleteButton="true" />

    Additionally, I am constantly being asked about how to add a confirm dialog box to the delete button.  You can use the following code on the RowDataBound event to add the confirmation.

     If e.Row.RowType = DataControlRowType.DataRow Then
        Dim lnk As LinkButton = e.Row.Cells(1).Controls(0)
        lnk.OnClientClick = "if(!confirm('Are you sure you want to delete this?')) return false;"
     End If

    I hope this helps!

  • Re: GridView RowDeleting event fires twice ! (My Solution)

    06-19-2007, 11:37 PM
    • Member
      48 point Member
    • dstorfer
    • Member since 04-25-2003, 11:40 AM
    • Buffalo, NY
    • Posts 12

    WOW!!

    That is definitely a "thinking outside the box" solution.  Bravo!! Yes

    Also - for confirmation boxes on those things, the new AJAX toolkit from Microsoft has a button confirmation control that's easy to use.  Same result as that simple code above, but a little more "design-timey" (and probably a lot more fat on the client with all those scripts, but eh, who cares about that now that everyone has fiber into their homes :-p).

Page 1 of 2 (29 items) 1 2 Next >