This is a migrated thread and some comments may be shown as answers.

RadGrid_InsertCommand double update

5 Answers 254 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Chuck Harrington
Top achievements
Rank 1
Chuck Harrington asked on 25 Mar 2011, 10:14 PM
I am trying to accomplish using a single Radgrid for 7 different tables.  (one aspx page)  I am also wrapping my datasource updates (CRUD) in a Property procedure.  It is working pretty well except for inserting a new row in a table.  My problem is that it is posting the update to the radgrid control and the database twice,  I have spent many hours trying to debug my problem using the call stack and various other methods and what I have determined is that when I press the Insert link button (in-place editing), it is running the Radgrid_InsertCommand procedure twice and I am going slowly mad trying to figure out why.  My code is attached,  This could be a real challenge for the telerik MVPs. (or not!)  Thanks in advance.  (if I could, I would award 1000 points - but that's another site ;->)
P.S.  The Delete and Update commands work just fine using this code.  The difference is the insert process is activated from a RadButton outside the grid.  My aspx file has only the OnInsert, OnDelete, OnUpdate Commands.and the various SQLDataSources  The grid columns are built dynamically in code behind depending on the table the user chooses.
Protected Sub rgDisplay_InsertCommand(sender As Object, e As Telerik.Web.UI.GridCommandEventArgs) Handles rgDisplay.InsertCommand
        Dim editeditem As GridEditableItem = CType(e.Item, GridEditableItem)
        Dim dataTbl As DataTable = Me.GridSource
        Dim newRow As DataRow = dataTbl.NewRow
  
            Try 'calculate the next record key
                cmd.CommandText = "SELECT MAX(CMT_REC_ID) FROM tblTSComments"
                cmd.Connection = conn
                conn.Open()
                intLastKey = Convert.ToInt16(cmd.ExecuteScalar().ToString)
                intLastKey += 1
            Finally
                conn.Close()
            End Try
  
            Dim newValues As Hashtable = New Hashtable
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editeditem)
            Try
                For Each entry As DictionaryEntry In newValues
                    If entry.Key = "CMT_REC_ID" Then
                        newRow("CMT_REC_ID") = intLastKey
                    Else
                        newRow(entry.Key) = entry.Value
                    End If
                Next
                dataTbl.Rows.Add(newRow)
                Me.GridSource = dataTbl
            Catch ex As Exception
                ' Error message goes here
                e.Canceled = True
            End Try
    End Sub
Private Property GridSource As DataTable
        Get
            Dim obj As Object = Me.ViewState("_gvs")
            If (Not obj Is Nothing) Then
                Return CType(obj, DataTable)
            Else
                Dim intRpt As Integer = Request("Report")
                Select Case intRpt
                    Case 0 'Comments
                        adp.SelectCommand = New OleDbCommand("SELECT CMT_REC_ID, CMT_DESCRIPTION FROM tblTSComments", conn)
                        Dim cmtstbl As New DataTable
                        conn.Open()
                        Try
                            adp.Fill(cmtstbl)
                        Finally
                            conn.Close()
                        End Try
                        Me.ViewState("_gvs") = cmtstbl
                        Return cmtstbl
                    Case 1 'Teams
                        adp.SelectCommand = New OleDbCommand("SELECT CT_TEAM_REC_ID, CT_TEAM_NAME, CT_REPORTS_TO FROM tblControllerTeam", conn)
                        Dim teamTbl As New DataTable
                        conn.Open()
                        Try
                            adp.Fill(teamTbl)
                        Finally
                            conn.Close()
                        End Try
                        Me.ViewState("_gvs") = teamTbl
                        Return teamTbl
                    Case 2 'Status
                        adp.SelectCommand = New OleDbCommand("SELECT TCS_STATUS_CODE, TCS_DESCRIPTION FROM tblEmplStatus", conn)
                        Dim statusTbl As New DataTable
                        conn.Open()
                        Try
                            adp.Fill(statusTbl)
                        Finally
                            conn.Close()
                        End Try
                        Me.ViewState("_gvs") = statusTbl
                        Return statusTbl
                    Case 3 'PayPeriod
                        adp.SelectCommand = New OleDbCommand("SELECT PAYPERIOD, PAYPERIODNBR, PAYPERIODLOCKED, PAYPERIODLOCKEDDATE, PAYPERIODLOCKID FROM PayPeriods ORDER BY PAYPERIOD", conn)
                        Dim ppTbl As New DataTable
                        conn.Open()
                        Try
                            adp.Fill(ppTbl)
                        Finally
                            conn.Close()
                        End Try
                        Me.ViewState("_gvs") = ppTbl
                        Return ppTbl
                    Case 4 'Team Leader
                        adp.SelectCommand = New OleDbCommand("SELECT OPF_NTUSER_ID, OPF_FNAME, OPF_MINIT, OPF_LNAME, OPF_REGION FROM tblOpsFacilitator", conn)
                        Dim leadTbl As New DataTable
                        conn.Open()
                        Try
                            adp.Fill(leadTbl)
                        Finally
                            conn.Close()
                        End Try
                        Me.ViewState("_gvs") = leadTbl
                        Return leadTbl
                    Case 5 'Vacation and Pers Choice Available
                        adp.SelectCommand = New OleDbCommand("SELECT TTE_NTUSER_ID, TTE_SOCIAL_SECURITY_NBR, TTE_FNAME + ' ' + TTE_LNAME AS NAME, TTE_TOTL_VAC_AVAIL, TTE_TOTL_PERS_CHOICE_AVAIL FROM tblTCCTimeCardEmployees WHERE TTE_EMPL_STATUS = 'A' ORDER BY TTE_NTUSER_ID", conn)
                        Dim vacPCHTbl As New DataTable
                        conn.Open()
                        Try
                            adp.Fill(vacPCHTbl)
                        Finally
                            conn.Close()
                        End Try
                        Me.ViewState("_gvs") = vacPCHTbl
                        Return vacPCHTbl
                    Case 6 'Rates
                        adp.SelectCommand = New OleDbCommand("SELECT TTE_NTUSER_ID, TTE_SOCIAL_SECURITY_NBR, TTE_FNAME + ' ' + TTE_LNAME AS NAME, TTE_EMPL_CATEGORY, TTE_CALC_TIMESHEET, TTE_FIVE_PCNT_RATE, TTE_TEN_PCNT_RATE FROM tblTCCTimeCardEmployees WHERE TTE_EMPL_STATUS = 'A' ORDER BY TTE_NTUSER_ID", conn)
                        Dim rateTbl As New DataTable
                        conn.Open()
                        Try
                            adp.Fill(rateTbl)
                        Finally
                            conn.Close()
                        End Try
                        Me.ViewState("_gvs") = rateTbl
                        Return rateTbl
                End Select
            End If
        End Get
        Set(value As DataTable)
            Dim intRpt As Integer = Request("Report")
            Select Case intRpt
                Case 0 'Comments
                    Try
                        adp.SelectCommand = New OleDbCommand("SELECT CMT_REC_ID, CMT_DESCRIPTION FROM tblTSComments", conn)
                        Dim cmdBldr As OleDbCommandBuilder = New OleDbCommandBuilder(adp)
                        conn.Open()
                        adp.Update(value)
                    Catch ex As Exception
                        'Error during update, add code to locate error, reconcile and try again
                    Finally
                        conn.Close()
                    End Try
                Case 1 'Teams
                    Try
                        adp.SelectCommand = New OleDbCommand("SELECT CT_TEAM_REC_ID, CT_TEAM_NAME, CT_REPORTS_TO FROM tblControllerTeam", conn)
                        Dim cmdBldr As OleDbCommandBuilder = New OleDbCommandBuilder(adp)
                        conn.Open()
                        adp.Update(value)
                    Catch ex As Exception
                        'Error during update, add code to locate error, reconcile and try again
                    Finally
                        conn.Close()
                    End Try
                Case 2 'Status
                    Try
                        adp.SelectCommand = New OleDbCommand("SELECT TCS_STATUS_CODE, TCS_DESCRIPTION FROM tblEmplStatus", conn)
                        Dim cmdBldr As OleDbCommandBuilder = New OleDbCommandBuilder(adp)
                        conn.Open()
                        adp.Update(value)
                    Catch ex As Exception
                        'Error during update, add code to locate error, reconcile and try again
                    Finally
                        conn.Close()
                    End Try
                Case 3 'PayPeriod
                    Try
                        adp.SelectCommand = New OleDbCommand("SELECT PAYPERIOD, PAYPERIODNBR, PAYPERIODLOCKED, PAYPERIODLOCKEDDATE, PAYPERIODLOCKID FROM PayPeriods ORDER BY PAYPERIOD", conn)
                        Dim cmdBldr As OleDbCommandBuilder = New OleDbCommandBuilder(adp)
                        conn.Open()
                        adp.Update(value)
                    Catch ex As Exception
                        'Error during update, add code to locate error, reconcile and try again
                    Finally
                        conn.Close()
                    End Try
                Case 4 'Team Leader
                    Try
                        adp.SelectCommand = New OleDbCommand("SELECT OPF_NTUSER_ID, OPF_FNAME, OPF_MINIT, OPF_LNAME, OPF_REGION FROM tblOpsFacilitator", conn)
                        Dim cmdBldr As OleDbCommandBuilder = New OleDbCommandBuilder(adp)
                        conn.Open()
                        adp.Update(value)
                    Catch ex As Exception
                        'Error during update, add code to locate error, reconcile and try again
                    Finally
                        conn.Close()
                    End Try
                Case 5 'Vacation and Pers Choice Available
                    Try
                        adp.SelectCommand = New OleDbCommand("SELECT TTE_NTUSER_ID, TTE_SOCIAL_SECURITY_NBR, TTE_FNAME + ' ' + TTE_LNAME AS NAME, TTE_TOTL_VAC_AVAIL, TTE_TOTL_PERS_CHOICE_AVAIL FROM tblTCCTimeCardEmployees WHERE TTE_EMPL_STATUS = 'A' ORDER BY TTE_NTUSER_ID", conn)
                        Dim cmdBldr As OleDbCommandBuilder = New OleDbCommandBuilder(adp)
                        conn.Open()
                        adp.Update(value)
                    Catch ex As Exception
                        'Error during update, add code to locate error, reconcile and try again
                    Finally
                        conn.Close()
                    End Try
                Case 6 'Rates
                    Try
                        adp.SelectCommand = New OleDbCommand("SELECT TTE_NTUSER_ID, TTE_SOCIAL_SECURITY_NBR, TTE_FNAME + ' ' + TTE_LNAME AS NAME, TTE_EMPL_CATEGORY, TTE_CALC_TIMESHEET, TTE_FIVE_PCNT_RATE, TTE_TEN_PCNT_RATE FROM tblTCCTimeCardEmployees WHERE TTE_EMPL_STATUS = 'A' ORDER BY TTE_NTUSER_ID", conn)
                        Dim cmdBldr As OleDbCommandBuilder = New OleDbCommandBuilder(adp)
                        conn.Open()
                        adp.Update(value)
                    Catch ex As Exception
                        'Error during update, add code to locate error, reconcile and try again
                    Finally
                        conn.Close()
                    End Try
            End Select
        End Set
    End Property
  
    Protected Sub cmdAdd_Click(sender As Object, e As System.EventArgs) Handles cmdAdd.Click
        rgDisplay.MasterTableView.InsertItem()
    End Sub
End Class

5 Answers, 1 is accepted

Sort by
0
Chuck Harrington
Top achievements
Rank 1
answered on 28 Mar 2011, 08:43 PM
Additional information to my original post.  It seems that not only is the RadGrid InsertCommand event executing twice but also the UpdateCommand and the DeleteCommand.  Coding in the delete command event prevents it from trying to delete an already deleted row, but the update command posts the update twice to the same record in the RadGrid as well as the database.  The Edit command is executed from a GridEditCommandColumn within the grid, while the Delete command is executed from a GridButtonColumn.  AllowautomaticUpdate, Delete and Insert are all set to false, but the events still fire twice.  Neither the edit mode nor the insert mode  disappear from the grid until after the second execution of the event is completed.  I have reviewed the Event sequence from the documentation and still cannot figure out why the events are firing twice.  The sequence is as follows
For Updates or Inserts: (in-place editing)
1. Enter new or updated data
2  click Update or Insert link button
3. InsertCommand or UpdateCommand fires
4. Row in Grid is updated.(see code in prior post for  examples)
5. Property Procedure (GridSource) is invoked from the Insert or Update event
6. Property Procedure executes update the datasource (OleDB).  commandbuilder used to generate Insert Update Delete
7. Return from Property procedure and execute the invoked event a second time causing double inserts (primary key recalculated)
    or update of the same record in the Grid and datasource twice.
8.  At end of second execution of the event, the NeedDataSource fires twice (This event invokes the Get side of the Property Procedure and reloads the RadGrid.  Only at this point, does the Edit Mode disappear and the Grid returns to an unedited state.
Could someone at Telerik, please explain why this is happening.  I can find no reason why it should.  I will be happy to open a ticket and submit sample website project so that you can attempt to duplicate the situation.  Thank you.
0
Vasil
Telerik team
answered on 31 Mar 2011, 02:19 PM
Hello,

I tried to replicate your issue but with no success.
Could you show us the declaration of your grid and the cmdAdd button? Are you using any update panels in your page? Could you also set a breaking point into cmdAdd_Click function and tell us how many times the function is called.

Greetings,
Vasil
the Telerik team
0
Chuck Harrington
Top achievements
Rank 1
answered on 04 Apr 2011, 04:05 PM
I did as you suggested with the break in the cmdAdd button.  Here is the code stipping sequence:
1.  cmdAdd_Click
2. Grid_Need_DataSource (executed twice)
3. cmdAdd_Click (Displays in-place edit mode)
4. New data entered here
5. click on Insert hyperlink button
6. executes Grid_InsertCommand procedure twice.
7. results is double entry of new data, each with unique record key.  It is recalculated each time in Insert procedure.  (see above code)
Grid and cmdAdd definition code follows:
<%@ Page Title="" Language="VB" MasterPageFile="~/Masters/Detail.master" AutoEventWireup="false" CodeFile="TablesDisplay.aspx.vb" Inherits="TablesDisplay" %>
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
  
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="mainContent" Runat="Server">
    <telerik:RadGrid ID="rgDisplay" runat="server"
     OnUpdateCommand="rgDisplay_UpdateCommand"
     OnDeleteCommand="rgDisplay_DeleteCommand"
     OnInsertCommand="rgDisplay_InsertCommand"
     OnNeedDataSource="rgDisplay_NeedDataSource" EnableLinqExpressions="False" 
     CellSpacing="0" GridLines="None">
     </telerik:RadGrid>
    <telerik:RadButton ID="cmdAdd" runat="server" Text="Add New" 
        Image-EnableImageButton="True" CommandName="AddButton" 
        EnableBrowserButtonStyle="True" Skin="Hay" Width="100px" Height="25px" 
        Font-Bold="True" Font-Names="Verdana" ForeColor="Black" >
        <Image EnableImageButton="True" IsBackgroundImage="True" ImageUrl="App_Themes/TCCTimesheets/Images/des_button_100x22.png" />
     </telerik:RadButton>
    <asp:SqlDataSource ID="CommentsDS" runat="server" 
        ConnectionString="<%$ ConnectionStrings:TCCTimesheetsConnectionString %>" 
        ProviderName="<%$ ConnectionStrings:TCCTimesheetsConnectionString.ProviderName %>"
        OldValuesParameterFormatString="orig_{0}"
        SelectCommand="SELECT CMT_REC_ID, CMT_DESCRIPTION FROM tblTSComments">
    </asp:SqlDataSource>
    <asp:SqlDataSource ID="TeamsDS" runat="server" 
        ConnectionString="<%$ ConnectionStrings:TCCTimesheetsConnectionString %>" 
        ProviderName="<%$ ConnectionStrings:TCCTimesheetsConnectionString.ProviderName %>"
        SelectCommand="SELECT CT_TEAM_REC_ID, CT_TEAM_NAME, CT_REPORTS_TO FROM tblControllerTeam">
    </asp:SqlDataSource>
    <asp:SqlDataSource ID="EmplStatusDS" runat="server" 
        ConnectionString="<%$ ConnectionStrings:TCCTimesheetsConnectionString %>" 
        ProviderName="<%$ ConnectionStrings:TCCTimesheetsConnectionString.ProviderName %>"
        SelectCommand="SELECT TCS_STATUS_CODE, TCS_DESCRIPTION FROM tblEmplStatus">
    </asp:SqlDataSource>
    <asp:SqlDataSource ID="PayPeriodDS" runat="server" 
        ConnectionString="<%$ ConnectionStrings:TCCTimesheetsConnectionString %>" 
        ProviderName="<%$ ConnectionStrings:TCCTimesheetsConnectionString.ProviderName %>"
        SelectCommand="SELECT PAYPERIOD, PAYPERIODNBR, PAYPERIODLOCKED, PAYPERIODLOCKEDDATE, PAYPERIODLOCKID FROM PayPeriods ORDER BY PAYPERIOD">
    </asp:SqlDataSource>
    <asp:SqlDataSource ID="OpsLeadDS" runat="server" 
        ConnectionString="<%$ ConnectionStrings:TCCTimesheetsConnectionString %>" 
        ProviderName="<%$ ConnectionStrings:TCCTimesheetsConnectionString.ProviderName %>"
        SelectCommand="SELECT OPF_NTUSER_ID, OPF_FNAME, OPF_MINIT, OPF_LNAME, OPF_REGION FROM tblOpsFacilitator">
    </asp:SqlDataSource>
    <asp:SqlDataSource ID="VacAvailDS" runat="server" 
        ConnectionString="<%$ ConnectionStrings:TCCTimesheetsConnectionString %>" 
        ProviderName="<%$ ConnectionStrings:TCCTimesheetsConnectionString.ProviderName %>"
        SelectCommand="SELECT TTE_NTUSER_ID, TTE_SOCIAL_SECURITY_NBR, TTE_FNAME + ' ' + TTE_LNAME AS NAME, TTE_TOTL_VAC_AVAIL, TTE_TOTL_PERS_CHOICE_AVAIL FROM tblTCCTimeCardEmployees WHERE TTE_EMPL_STATUS = 'A' ORDER BY TTE_NTUSER_ID">
    </asp:SqlDataSource>
    <asp:SqlDataSource ID="PcntRateDS" runat="server" 
        ConnectionString="<%$ ConnectionStrings:TCCTimesheetsConnectionString %>" 
        ProviderName="<%$ ConnectionStrings:TCCTimesheetsConnectionString.ProviderName %>"
        SelectCommand="SELECT TTE_NTUSER_ID, TTE_SOCIAL_SECURITY_NBR, TTE_FNAME + ' ' + TTE_LNAME AS NAME, TTE_EMPL_CATEGORY, TTE_CALC_TIMESHEET, TTE_FIVE_PCNT_RATE, TTE_TEN_PCNT_RATE FROM tblTCCTimeCardEmployees WHERE TTE_EMPL_STATUS = 'A' ORDER BY TTE_NTUSER_ID">
    </asp:SqlDataSource>
</asp:Content>
 Please refer to prior posts for rest of code and comments.  Thanks again for reviewing this.  I am not using a panel.
0
Vasil
Telerik team
answered on 06 Apr 2011, 03:14 PM
Hello Chuck,

Grid_InsertCommand is executed twice, because it is attached twice to the grid's InsertCommand command. It is the same situation with Grid_Need_DataSource.

Once you have attached the Grid_InsertCommand in the grid's declaration in the aspx markup:
<telerik:RadGrid ID="rgDisplay" runat="server"
     OnUpdateCommand="rgDisplay_UpdateCommand"
     OnDeleteCommand="rgDisplay_DeleteCommand"
     OnInsertCommand="rgDisplay_InsertCommand"
.......... />
And the other time in method declaration in the code-behind:
Protected Sub rgDisplay_InsertCommand(sender As Object, e As Telerik.Web.UI.GridCommandEventArgs) Handles rgDisplay.InsertCommand
        Dim editeditem As GridEditableItem = CType(e.Item, GridEditableItem)
        Dim dataTbl As DataTable = Me.GridSource
        Dim newRow As DataRow = dataTbl.NewRow
You should use only one of the approaches above and the rgDisplay_InsertCommand will be fired only once. So for example remove "Handles rgDisplay.InsertCommand" from the method's declaration and all should work fine.

Best wishes,
Vasil
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
Chuck Harrington
Top achievements
Rank 1
answered on 07 Apr 2011, 03:33 PM
Thanks Vasil.  That fix did it.
Tags
Grid
Asked by
Chuck Harrington
Top achievements
Rank 1
Answers by
Chuck Harrington
Top achievements
Rank 1
Vasil
Telerik team
Share this question
or