locked
Gridview Error After Adding New Record and trying to make other edits/updates/cancels or deletes RRS feed

  • Question

  • User-762279931 posted

    Hello,

    I am trying to create a simple contact database web app using Gridview, teaching myself as I go. Caveat: I am not a programmer and am just learning Visual Studio Community 2015. I have cobbled together the app based on my readings online and several different tutorials.

    Here is my issue: When I run the app, I can edit, update, cancel and delete records and I can insert a new record. The problem is that AFTER I insert a new record, I cannot do anything else as I get an error. If I try to edit a record after the add I get the "GridView 'GridViewContacts' fired event RowEditing which wasn't handled." error, or if I try to delete a record, I get the corresponding "GridView 'GridViewContacts' fired event RowDeleting which wasn't handled." error. With the deleting, this error happens after my return confirm message is displayed and ok is clicked.

    Here is my design side code:

    <%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="DatabaseGridPage.aspx.vb" Inherits="WebApp050916.DatabaseGridPage" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
        <h2><%: Title %>Record Info</h2>
        <p>
            <asp:GridView ID="GridViewContacts" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="SqlDataSource1" ShowFooter="True" OnRowCommand="GridViewContacts_RowCommand">
                <Columns>
                    <asp:TemplateField ShowHeader="False">
                        <EditItemTemplate>
                            <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
                            &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
                        </EditItemTemplate>
                        <FooterTemplate>
                            <asp:Button ID="btnAddNewRecord" runat="server" CausesValidation="False" CommandName="AddNew" Text="Add New Record" />
                        </FooterTemplate>
                        <ItemTemplate>
                            <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
                            &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete" OnClientClick="return confirm ('Are you sure you want to delete the record?');"></asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Id" InsertVisible="False" SortExpression="Id">
                        <EditItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Eval("Id") %>'></asp:Label>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Bind("Id") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="FirstName" SortExpression="FirstName">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("FirstName") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="txtAddFirstName" runat="server"></asp:TextBox>
                        </FooterTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="LastName" SortExpression="LastName">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("LastName") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="txtAddLastName" runat="server"></asp:TextBox>
                        </FooterTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label3" runat="server" Text='<%# Bind("LastName") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Company" SortExpression="Company">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Company") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="txtAddCompany" runat="server"></asp:TextBox>
                        </FooterTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label4" runat="server" Text='<%# Bind("Company") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Phone" SortExpression="Phone">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Phone") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="txtAddPhone" runat="server"></asp:TextBox>
                        </FooterTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label5" runat="server" Text='<%# Bind("Phone") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Email" SortExpression="Email">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("Email") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="txtAddEmail" runat="server"></asp:TextBox>
                        </FooterTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label6" runat="server" Text='<%# Bind("Email") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues" ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>" 
                DeleteCommand="DELETE FROM [Contacts] WHERE [Id] = @original_Id AND (([FirstName] = @original_FirstName) OR ([FirstName] IS NULL AND @original_FirstName IS NULL)) AND (([LastName] = @original_LastName) OR ([LastName] IS NULL AND @original_LastName IS NULL)) AND (([Company] = @original_Company) OR ([Company] IS NULL AND @original_Company IS NULL)) AND (([Phone] = @original_Phone) OR ([Phone] IS NULL AND @original_Phone IS NULL)) AND (([Email] = @original_Email) OR ([Email] IS NULL AND @original_Email IS NULL))" 
                InsertCommand="INSERT INTO [Contacts] ([FirstName], [LastName], [Company], [Phone], [Email]) VALUES (@FirstName, @LastName, @Company, @Phone, @Email)" OldValuesParameterFormatString="original_{0}" 
                SelectCommand="SELECT * FROM [Contacts]" 
                UpdateCommand="UPDATE [Contacts] SET [FirstName] = @FirstName, [LastName] = @LastName, [Company] = @Company, [Phone] = @Phone, [Email] = @Email WHERE [Id] = @original_Id AND (([FirstName] = @original_FirstName) OR ([FirstName] IS NULL AND @original_FirstName IS NULL)) AND (([LastName] = @original_LastName) OR ([LastName] IS NULL AND @original_LastName IS NULL)) AND (([Company] = @original_Company) OR ([Company] IS NULL AND @original_Company IS NULL)) AND (([Phone] = @original_Phone) OR ([Phone] IS NULL AND @original_Phone IS NULL)) AND (([Email] = @original_Email) OR ([Email] IS NULL AND @original_Email IS NULL))">
                <DeleteParameters>
                    <asp:Parameter Name="original_Id" Type="Int32" />
                    <asp:Parameter Name="original_FirstName" Type="String" />
                    <asp:Parameter Name="original_LastName" Type="String" />
                    <asp:Parameter Name="original_Company" Type="String" />
                    <asp:Parameter Name="original_Phone" Type="String" />
                    <asp:Parameter Name="original_Email" Type="String" />
                </DeleteParameters>
                <InsertParameters>
                    <asp:Parameter Name="FirstName" Type="String" />
                    <asp:Parameter Name="LastName" Type="String" />
                    <asp:Parameter Name="Company" Type="String" />
                    <asp:Parameter Name="Phone" Type="String" />
                    <asp:Parameter Name="Email" Type="String" />
                </InsertParameters>
                <UpdateParameters>
                    <asp:Parameter Name="FirstName" Type="String" />
                    <asp:Parameter Name="LastName" Type="String" />
                    <asp:Parameter Name="Company" Type="String" />
                    <asp:Parameter Name="Phone" Type="String" />
                    <asp:Parameter Name="Email" Type="String" />
                    <asp:Parameter Name="original_Id" Type="Int32" />
                    <asp:Parameter Name="original_FirstName" Type="String" />
                    <asp:Parameter Name="original_LastName" Type="String" />
                    <asp:Parameter Name="original_Company" Type="String" />
                    <asp:Parameter Name="original_Phone" Type="String" />
                    <asp:Parameter Name="original_Email" Type="String" />
                </UpdateParameters>
            </asp:SqlDataSource>
        </p>
    
    </asp:Content>

    And here is my code behind:

    Imports System.Data.SqlClient
    
    Public Class DatabaseGridPage
        Inherits System.Web.UI.Page
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load, GridViewContacts.Load
    
        End Sub
    
        Dim conn As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\32a925\Documents\Visual Studio 2015\Projects\WebApp050916\WebApp050916\App_Data\Contacts.mdf;Integrated Security=True")
        Dim ad As New SqlDataAdapter()
        Dim cmd As New SqlCommand()
        Dim dataTable As DataTable
    
        Private Sub FillGrid()
    
            dataTable = New DataTable()
            cmd.Connection = conn
            cmd.CommandText = "SELECT * FROM contacts"
            ad = New SqlDataAdapter(cmd)
            ad.Fill(dataTable)
            GridViewContacts.DataSource = dataTable
            GridViewContacts.DataSourceID = String.Empty
            GridViewContacts.DataBind()
    
        End Sub
    
        Protected Sub GridViewContacts_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) Handles GridViewContacts.RowCommand
    
            If e.CommandName.Equals("AddNew") Then
                Dim txtAddFirstName As TextBox = DirectCast(GridViewContacts.FooterRow.FindControl("txtAddFirstName"), TextBox)
                Dim txtAddLastName As TextBox = DirectCast(GridViewContacts.FooterRow.FindControl("txtAddLastName"), TextBox)
                Dim txtAddCompany As TextBox = DirectCast(GridViewContacts.FooterRow.FindControl("txtAddCompany"), TextBox)
                Dim txtAddPhone As TextBox = DirectCast(GridViewContacts.FooterRow.FindControl("txtAddPhone"), TextBox)
                Dim txtAddEmail As TextBox = DirectCast(GridViewContacts.FooterRow.FindControl("txtAddEmail"), TextBox)
    
                cmd.Connection = conn
                cmd.CommandText = (("INSERT INTO Contacts(FirstName,LastName,Company,Phone,Email) Values('" + txtAddFirstName.Text & "','" + txtAddLastName.Text & "','" + txtAddCompany.Text & "','" + txtAddPhone.Text & "','" + txtAddEmail.Text & "')"))
                conn.Open()
                cmd.ExecuteNonQuery()
                FillGrid()
                conn.Close()
            End If
    
        End Sub
    
    End Class

    Obviously, I have "extra" code regarding my insert that I can probably get rid of. But, what am I missing that is causing the errors? I didn't think that I had to add OnRowEditing or OnRowDeleting as these were being taken care of on the design side. Any help or suggestions would be very much appreciated!

    Thank you!

    Thursday, May 19, 2016 2:58 PM

Answers

All replies

  • User2103319870 posted

    <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton> &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete" OnClientClick="return confirm ('Are you sure you want to delete the record?');"></asp:LinkButton>

    You have set the CommandName for each button. if you have a button with commandname set like Delete or Edit will fire the gridview related events for Edit and Delete. One solution is to create empty events for each of these operations like below

    ''' <summary>
        ''' Handles the RowEditing event of the GridViewContacts control.
        ''' </summary>
        ''' <param name="sender">The source of the event.</param>
        ''' <param name="e">The <see cref="GridViewEditEventArgs"/> instance containing the event data.</param>
        Protected Sub GridViewContacts_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles GridViewContacts.RowEditing
    
        End Sub
    
        ''' <summary>
        ''' Handles the RowDeleting event of the GridViewContacts control.
        ''' </summary>
        ''' <param name="sender">The source of the event.</param>
        ''' <param name="e">The <see cref="GridViewDeleteEventArgs"/> instance containing the event data.</param>
        Protected Sub GridViewContacts_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles GridViewContacts.RowDeleting
    
        End Sub

    Thursday, May 19, 2016 4:39 PM
  • User-762279931 posted

    Hi A2H,

    Thanks so much for the reply. So, I have done as you suggested and added empty row editing and deleting events. I also added updating and canceling as well, assuming I need those as well for the Update and Cancel buttons?

    Added on design side:

    OnRowEditing="GridViewContacts_RowEditing" OnRowDeleting="GridViewContacts_RowDeleting" OnRowUpdating="GridViewContacts_RowUpdating" OnRowCancelingEdit="GridViewContacts_RowCancelingEdit"

    Added to code behind:

        Protected Sub GridViewContacts_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles GridViewContacts.RowUpdating
    
        End Sub
    
        Protected Sub GridViewContacts_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles GridViewContacts.RowCancelingEdit
    
        End Sub
    
    
        Protected Sub GridViewContacts_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles GridViewContacts.RowEditing
    
        End Sub
    
        Protected Sub GridViewContacts_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles GridViewContacts.RowDeleting
    
        End Sub

    However, now when I run it, it gets interesting. Everything again, works just fine, until you try to do something AFTER adding a new record. The new record adds ok, but then if I click Edit on another record, nothing happens. If I click that same Edit button again, it throws it into Edit mode (which, of course it should do after the first click) and displays the Update and Cancel buttons. You can make changes to the record then, but clicking Update does NOT record the changes, and clicking Cancel does NOT rescind the changes. If you then click, say, the delete button on a different record, the record that you were previously trying to Update or Cancel disappears from the grid and the new record goes into Edit mode, but with the same issues as above.

    Ideas? I get that something somewhere likely needs binding, but have no idea what code is needed where. Frown

    Thursday, May 19, 2016 8:00 PM
  • User36583972 posted

    Hi MelBOC,

    I found some tutorials about a series of operations (Add, Edit and delete) in GridView. It will help you better understand these operations. You can refer the following links.

    1: Insert Update Edit Delete record in GridView using SqlDataSource in ASP.Net:

    http://www.aspsnippets.com/Articles/Insert-Update-Edit-Delete-record-in-GridView-using-SqlDataSource-in-ASPNet.aspx

    2: Gridview - Add, Edit and delete:

    http://asp.net-informations.com/gridview/gridview-operations.htm

    3: Asp.net: add, edit, delete and update record in Gridview control:

    http://www.articlemirror.in/2015/08/gridview-add-edit-delete-and-update-record-asp.net-c-vb.net.html

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 20, 2016 9:46 AM
  • User-762279931 posted

    Hi Yohann Lu,

    Thanks very much for the links. I appreciate your taking the time to locate them for me. Am looking at them now. Smile

    Friday, May 20, 2016 3:52 PM