locked
GridView RowDeleting event fires twice ! RRS feed

  • Question

  • User603221718 posted

    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

     

    Sunday, June 25, 2006 7:25 PM

All replies

  • User603221718 posted
    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.
    Monday, June 26, 2006 6:22 AM
  • User603221718 posted

    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.
    Monday, June 26, 2006 2:50 PM
  • User-338583042 posted

    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.

    Thursday, July 6, 2006 4:06 PM
  • User458160347 posted
    Hi
    I'm having this problem too. I will try your solutions. Thanks very much !

    Wednesday, August 2, 2006 3:51 AM
  • User603221718 posted

    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).<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p></o:p>

    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.<o:p></o:p>

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

    <asp:TemplateField><o:p></o:p>

    <ItemStyle HorizontalAlign="Right" Width="10%"/><o:p></o:p>

    <ItemTemplate><o:p></o:p>

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

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

    </ItemTemplate><o:p></o:p>

    </asp:TemplateField><o:p></o:p>

    <o:p> </o:p>

    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.<o:p></o:p>

    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”)<o:p></o:p>

    And here is the code behind for handling the event “OnDelete”:<o:p></o:p>

    protected void OnDelete(object sender, CommandEventArgs e)<o:p></o:p>

        {<o:p></o:p>

            if (e.CommandName.Equals("cDelete")) <o:p></o:p>

            {<o:p></o:p>

                try<o:p></o:p>

                {<o:p></o:p>

                    string item_id = e.CommandArgument.ToString();<o:p></o:p>

                      // your code to delete the item record from <o:p></o:p>

    // your database using the index item_id<o:p></o:p>

    <o:p> </o:p>

                }<o:p></o:p>

                catch (Exception) { }<o:p></o:p>

            }<o:p></o:p>

        }<o:p></o:p>

    <o:p> </o:p>

    Thursday, August 3, 2006 4:54 PM
  • User-239885219 posted
    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.
    Monday, March 19, 2007 5:24 AM
  • User-239885219 posted

    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...

    Monday, March 19, 2007 5:29 AM
  • User-787043131 posted

    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.

    HTH[:|] 

    itsdanny 

    Thursday, April 12, 2007 8:12 AM
  • User1756476999 posted

    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() )); 
    } 
    
    
     
    Monday, April 23, 2007 1:21 AM
  • User1634336839 posted

    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!

    Thursday, May 3, 2007 2:23 AM
  • User1634336839 posted

    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

    Thursday, May 3, 2007 2:23 AM
  • User1017690648 posted

    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!

    Tuesday, June 19, 2007 6:27 PM
  • User1756476999 posted

    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).

    Tuesday, June 19, 2007 11:37 PM
  • User519246680 posted

    My solution is a slight variation.  If you're like me, you know how inefficient it is to use inline databinding (<%# Eval("item_id") %>).  Not only do you get a performance hit, but it makes your code ugly (don't even get me started on the repeater control).

    Instead, take out the Command Argument and change the Command Names of each button to what they default to in the GridView (ie:  Select, Edit, Update, Cancel, Delete).  This will fire the GridView's OnRow<insert command name here> event.  For instance, if your item template has an image button that is set up with a command name of "Delete", it will automatically fire the OnRowDeleting event for the GridView when clicked.  An example is below:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Test_Default" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <
    html xmlns="http://www.w3.org/1999/xhtml" >
    <
    head runat="server">
        <title>Untitled Page</title>
    </head>
    <
    body>
        <form id="form1" runat="server">
           
    <div>
               
    <asp:GridView ID="grdTest" runat="server" AutoGenerateColumns="False" OnRowDeleting="grdTest_RowDeleting" OnRowEditing="grdTest_RowEditing" OnSelectedIndexChanging="grdTest_SelectedIndexChanging">
                <Columns>

                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:ImageButton ID="btnView" runat="server" ImageUrl="~/images/view.png" CommandName="Select" OnCommand="btnView_OnView" AlternateText="View" />
                        </ItemTemplate>
                        <ItemStyle HorizontalAlign="Left" VerticalAlign="Top" />
                    </asp:TemplateField>

                    <asp:TemplateField>
                        <ItemTemplate>
                           
    <asp:ImageButton ID="btnEdit" runat="server" ImageUrl="~/images/edit.png" CommandName="Edit" OnCommand="btnEdit_OnEdit" AlternateText="Edit" />
                        </ItemTemplate>
                        <ItemStyle HorizontalAlign="Left" VerticalAlign="Top" />
                    </asp:TemplateField>

                    <asp:BoundField DataField="ProjectID" HeaderText="ID">
                        <HeaderStyle HorizontalAlign="Left" />
                        <ItemStyle HorizontalAlign="Left" VerticalAlign="Top" />
                    </asp:BoundField>

                    <asp:BoundField DataField="ProjectName" HeaderText="Project Name">
                        <HeaderStyle HorizontalAlign="Left" />
                        <ItemStyle HorizontalAlign="Left" VerticalAlign="Top" />
                    </asp:BoundField>

                    <asp:BoundField DataField="ProjectDescription" HeaderText="Description">
                       
    <ItemStyle Width="300px" Wrap="False" HorizontalAlign="Left" VerticalAlign="Top" />
                       
    <HeaderStyle HorizontalAlign="Left" />
                   
    </asp:BoundField>

                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:ImageButton ID="btnDelete" runat="server" ImageUrl="~/images/delete.png" CommandName="Delete" OnCommand="btnDelete_OnDelete" AlternateText="Delete" />
                        </ItemTemplate>
                        <ItemStyle HorizontalAlign="Left" VerticalAlign="Top" />
                    </asp:TemplateField>

                </Columns>
                </asp:GridView>

            </div>
        </form>
    </
    body>

    And the code-behind:

    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Web.UI.WebControls;

    public partial class Test_Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SqlConnection conn = new SqlConnection(connStr);
                conn.Open();

                SqlCommand comm = new SqlCommand();
                comm.Connection = conn;
                comm.CommandType =
    CommandType.Text;
                comm.CommandText =
    "Select * from Project";

                DataSet ds = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter(comm);

                da.Fill(ds);
                da.Dispose();

                comm.Dispose();

                conn.Close();
                conn.Dispose();

                grdTest.DataSource = ds;
                grdTest.DataBind();
            }
        }

        protected void btnView_OnView(object sender, CommandEventArgs e)
        {

        }

        protected void btnEdit_OnEdit(object sender, CommandEventArgs e)
        {

        }

        protected void btnDelete_OnDelete(object sender, CommandEventArgs e)
        {

        }

        protected void grdTest_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

        }

        protected void grdTest_RowEditing(object sender, GridViewEditEventArgs e)
        {

        }

        protected void grdTest_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {

        }
    }

    The biggest benefit (in my humble opinion) is that you can handle both the gridview events AND the imagebutton events, abstracting any business logic associated with clicking the button even further.

    Monday, June 25, 2007 2:08 PM
  • User2144021440 posted

    I am having this problem except I am using a DetailsView and an ObjectDataSource.  I mention the data source because I have been using SqlDataSources for sometime now and it hasn't been a problem.  Does anyone have suggestions about the DetailsView?  I don't want to change the field to a TemplateField because I want to keep the format. It closes off the bottom of the DetailsView nicely.  My post is here.

    http://forums.asp.net/p/1125936/1775818.aspx#1775818

    Wednesday, June 27, 2007 2:38 PM
  • User-1004164262 posted

    THANK YOU, what a great easy solution that required minimal work,..GREAT JOB!!

    Monday, July 23, 2007 10:15 PM
  • User303347921 posted

    Hi !!

    does anybody actually know if Visual Studio 2005 SP1 fix this GridView RowDeleting issue?

    meanwhile, I have a go with this workaround (converting the CommandField column to TemplateField) [cool]

    but I've got a strange error:

    Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
     

    Well, it's not my intention to change default configurations in my aspx page neither web.config.

    So I'll search for another workaround. Any comments? let me know! [:D]

    the good posts are awesome, thank you all!
     

    Sunday, August 19, 2007 5:33 PM
  • User1935984934 posted

    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.

    Great solution thanks. I was doing the same in the datagrid .NET 1.x. Hopefully a fix will be available soon.
    Thursday, September 27, 2007 8:55 PM
  • User1885678998 posted

     @Mimix: Really great, man! It's SO brilliant and slim at the same time. I was close to resign to this dumb ASP problem, but then I found this solution. How did you find out?

    The only problem is, you can't change the CommandName if you use those special fields. But for any other action not covered by CommandButton I use the other solution and put the PrimaryKey into the CommandArgument using the Eval function...

    Thanx again

    Peter 

    Thursday, February 14, 2008 1:41 PM
  • User1024734806 posted

    Hello Friends .....

    Here is Tag for GridView... 

     <asp:GridView ID="grdmember" runat="server" AutoGenerateColumns="False" Width="100%" OnRowCommand="grdmember_RowCommand" DataKeyNames="id"> 

     

     ANd following code shows CodeBehind Code

     

    Protected Sub grdmember_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grdmember.RowCommand 

     

    now here RowCommand Handler is Added Two times....

    1. Because of Tags  "OnRowCommand " Attribute

    2. Becuases of Handles grdmember.RowCommand

     

    And now when I was cliking Edit Button in grid I was facing the same problem...

    When i had removed... "OnRowCommand" Attribute from tag... Problem was solved..

     

    SO you can Check and try the same..

     

    Happy GridViewing.. [Yes][:D]

    Tuesday, April 15, 2008 5:57 AM
  • User-2002648249 posted

    Hi

    i faced the same problem.then i removed code ondeleting="gridviw1_deleting" from html and solve the problem .I dont know what is this.

    Tuesday, April 15, 2008 6:46 AM
  • User-1688580671 posted

    Thanks for this solution, really cleanest.

    Thanks all you for the other ways, this problem was freaking me out.

    Someone tested in 3.5 framework?

    Cheers

    Thursday, June 26, 2008 5:09 PM
  • User1065466015 posted

    Great Mimix !

    Its really out of the box soultion. Thanks a lot ! [:)]

     Danish Miyan

    Friday, November 7, 2008 6:02 AM
  • User-465811975 posted

    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).<o:p></o:p>

    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.<o:p></o:p>

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

    <asp:TemplateField><o:p></o:p>

    <ItemStyle HorizontalAlign="Right" Width="10%"/><o:p></o:p>

    <ItemTemplate><o:p></o:p>

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

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

    </ItemTemplate><o:p></o:p>

    </asp:TemplateField><o:p></o:p>

    <o:p> </o:p>

    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.<o:p></o:p>

    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”)<o:p></o:p>

    And here is the code behind for handling the event “OnDelete”:<o:p></o:p>

    protected void OnDelete(object sender, CommandEventArgs e)<o:p></o:p>

        {<o:p></o:p>

            if (e.CommandName.Equals("cDelete")) <o:p></o:p>

            {<o:p></o:p>

                try<o:p></o:p>

                {<o:p></o:p>

                    string item_id = e.CommandArgument.ToString();<o:p></o:p>

                      // your code to delete the item record from <o:p></o:p>

    // your database using the index item_id<o:p></o:p>

    <o:p> </o:p>

                }<o:p></o:p>

                catch (Exception) { }<o:p></o:p>

            }<o:p></o:p>

        }<o:p></o:p>

    <o:p> </o:p>

     

     

    Thanx Brad for this information! I was struggling with the command field of image type for some time, and with postbacks going twice..Couldn't use template field either because I got the dreaded "Invalid postback or callback argument". So, since my application uses Resource files for translations, I just put the img tag in the resource file, for the command field's text like this:

    pagename.aspx.resx -  Delete.DeleteText =<img src='../../images/icons/button_delete.gif' border=0>

    and the command field tag:

    <asp:CommandField ShowDeleteButton="true" CausesValidation="False" meta:ResourceKey="Delete" />

    the gridview has an OnRowDeleting event which fires when the image is clicked.

    I was also struggling to get a javascript confirm to the delete click (didn't really work in the OnRowDataBound event now because I used a image), thought I should test puttin it in the resource file text and it worked!! :

    <img src='../../images/icons/button_delete.gif' border=0 onClick="return confirm('Do you wish to delete this image?');">

     

     

    Wednesday, December 10, 2008 5:38 AM
  • User-1323718700 posted

    I have AutoEventWireup="false" in mine and its still firing twice.  I'm not using Master Pages in this particular application.

    Friday, March 13, 2009 5:59 PM
  • User2025590851 posted

     thanks, I did the change and it worked fine!!

    Thursday, May 21, 2009 1:36 PM
  • User-284097262 posted

    In my case, stop using SqlDataSource_Deleted event and removing the AutoEventWireup from .ASPX (both masterpage and actual page) solved the twice-call to my delete RowCommand code. Smile  Many hours spent on this.....  Cry 

    Thanks all for help!

     

    Sunday, December 6, 2009 11:06 PM
  • User-1115066090 posted

    Oh my!  You are awesome ItsDanny I am having this issue on many of my pages, and messing with autoeventwireup does nothing. 
    I have been using gvGridView.Clear();
    and trying many crazy (!ispostback){}; solutions working around the problem, but i feel dirty, and have trouble sleeping at night, because i know the page is running though my code twice.  I am doing some 70 000 queries on the page, and hate for that sql server to be doing it twice.  It has driven my crazy for months, and as soon as i read your post, i instantly doubled the speed of a dozen pages. 

    I have stepped through the code time and time again, but i could not figure out why pageload fires twice.  Now, I don;t care.  I feel like i just got a free lapdance at the stripclub.  Your are amazing.  Here is how i implemented your advice in C#  Thanks a million -jonjavajones

    public Boolean bExit = false;
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (bExit==true){return;}
    
        fnLoadABunchOfCrap();
        fnLoadABunchMoreCrap();
        fnFillATableFullofSomeCrazyQueries();
        fnFilltblComments();
    
    bExit=True;
    
    }
    


    Again, thanks a million! 

    Tuesday, January 12, 2010 1:39 PM
  • User1756476999 posted

    70,000 queries?!!  Are you really sure that your poor little SQL Server needs to do all that work? 

    Are you doing things like bringing data from SQL to your webpage, looping through it and then running queries against each row?   If so, you might really want to consider putting that into a stored procedure so that it runs all on SQL Server instead of trafficking all that data between servers.  You'd be surprised how powerful T-SQL is for that, but now - the fact is, you can even write a stored procedure in your favorite .NET language (although I have yet to do that since I'm pretty good at doing T-SQL).



    Tuesday, January 12, 2010 3:17 PM
  • User-1115066090 posted

    Ha ha, Yeah, i guess you might have guessed, i am not actually binding to a gridview, and i am using several stored procedures to build the page and render it in. 

    For your point, I am<?XML:NAMESPACE PREFIX = ASP /><ASP:CELLS> <ASP:Table>Admittedly an amature at SQL, so as i learn better queries, i need to write less code.

    The problem i was having, before itsdanny showed me a solution was the double rendering of page load, and many problem on this page, and 90 other pages i read before this one are not actually a problem with the gridview, or the dropdown box, or the delete command, it is some behavior i have not quite nailed down.

    It seems that somewhere in the page load life cycle, the page actually loads before it renders. Some dynamic creation of controls on the "Front End" cannot be referanced in the backend, till farther down the lifecycle, ie before the the page is loaded, but putting the identical code in the try catch loop often works. I am not sure why, but i have this theory, that try is executed before the page loads the first time, and catch seems to get executed after the first load?
    Weird, and it seems that when you are dynamicly filling front end controls with the back end code, they get filled twice??? It seems that the pageload fires twice. Now if people are deleting something from the gridview, and it loads the second time, the referanced thing is not there, thus the error that all these clever hacks attempt to code around.

    I think i lost myself. These problems people are having i think are often symptoms of the dual page load crazyness. Running pageload once, (ie forcing it to exit) solved all my problems, and would solve 90 percent of the crazy gridview issues.

    </ASP:Table></ASP:CELLS>
    Tuesday, January 12, 2010 4:00 PM
  • User-787043131 posted

    Hi the issue could be that you have an asp:imagebutton, with an onclick event, which posts back. The event it posts back to has a "Handles btnimage.click" on it, so the onClick fires then then handler. The solution should be to remove one of them (if this discribes your scenario), it doesn't matter which.

    Thanks

    Wednesday, January 13, 2010 3:51 AM
  • User94433302 posted

    I have form inside i put two tabcontainer having three tab

    when i click on button having code of insert into table 

    button event fired just once but record get inserted in database twice..


    help me if you know answer....

    plz i m waiting on kaushikhalvadiya@yahoo.co.in


    Friday, September 3, 2010 2:23 AM