[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Inserting a recored in twice when I click on the submit button in my asp.net gridview table

Posted on 2014-08-22
2
Medium Priority
?
375 Views
Last Modified: 2014-09-12
I have an applicaion that brings up a course roster in a Gridview table. I have a button on the row of the table that when clicked saves (inserts) the new record into the course rosted database table. The issue is that the record is submited two times (inserted two times). I looked over my code and I can not see where I have two insert statements. Need help ASAP.
My code is below:

ASP.NET Code:
   <asp:GridView ID="gvAddDeleteParticipants" runat="server" BackColor="White" BorderColor="#999999"  
                                                    BorderWidth="1px" DataKeyNames="ID" EmptyDataText="No match found!"
                                                    OnRowCancelingEdit="gvAddDeleteParticipants_RowCancelingEdit" 
                                                    CellPadding="3" ForeColor="Black" GridLines="Vertical" ShowFooter="true"
                                                    AutoGenerateColumns="false" OnRowDeleting="imgDeleteBtn"
                                                    BorderStyle="Ridge" Font-Size="9pt" OnSelectedIndexChanged="gvAddDeleteParticipants_SelectedIndexChanged" Height="334px">
                                            <FooterStyle BackColor="#CCCCCC" /> 
                                            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                                            <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                                            <HeaderStyle BackColor="#4CAEE3" ForeColor="White" />
                                            <RowStyle BackColor="#EBEBEB" ForeColor="Black" />
                                             <AlternatingRowStyle BackColor="White" ForeColor="Black" />
                                                <Columns>
                                                    <asp:TemplateField>
                                                        <ItemTemplate>
                                                           <%-- <asp:ImageButton ID="imgDeleteBtn" runat="server" ImageUrl="~/images/DeleteAttendee.png" Width="100px" CausesValidation="False"  CommandName="Delete" OnClientClick="javascript : return confirm('Do you really want to \nDelete this from roster?'); " Visible="false"/>--%>
                                                             <asp:ImageButton ID="imgDeleteBtn" runat="server" ImageUrl="~/images/DeleteAttendee.png" Width="100px" CausesValidation="False" CommandName="Delete"  OnClientClick="javascript : return confirm('Do you really want to \nDelete this from roster?'); " Visible="true"/> 
                                                        </ItemTemplate>
                                                       
                                                    </asp:TemplateField>                              
                                                    <asp:BoundField DataField="ID" HeaderText="Attendee ID" Visible="false"  /> 
                                                    <asp:TemplateField>
                                                        <ItemTemplate>
                                                            <asp:ImageButton ID="imgSaveBtn" runat="server" Width="100px" ImageUrl="~/images/SaveAttendee.png" OnClick="imgSaveBtn_Click" />  < ---- button that saves/inserts the new record
                                                        </ItemTemplate>
                                                        <%--<FooterTemplate>
                                                            <asp:ImageButton ID="btnCertificates" runat="server" ImageUrl="~/images/PrintCertificates.png" Width="100px" OnCommand="btnCertificates_Command" CommandArgument='<%#Eval ("CourseID") %>' />
                                                        </FooterTemplate>--%>
                                                    </asp:TemplateField>
                                                    <asp:TemplateField HeaderText="Course Number" >
                                                        <ItemTemplate>
                                                            <asp:Label ID="lblCourseID" runat="server" Text='<%# Bind("courseNumber") %>' Visible="true" /> 
                                                        </ItemTemplate>
                                                    </asp:TemplateField>

                                                     <asp:TemplateField HeaderText="Attendee ID">
                                                        <ItemTemplate>
                                                            <asp:TextBox ID="lblAttendeeID" runat="server" Text='<%# Bind("id") %>' Visible="true" Enabled="false" /> 
                                                        </ItemTemplate>
                                                    </asp:TemplateField>
                                                     <asp:TemplateField HeaderText="Agent Number">
                                                        <ItemTemplate>
                                                            <asp:Label ID="lblAgentNumber" runat="server" Text='<%# Bind("AGN_AGENT_NBR") %>' Visible="true" /> 
                                                        </ItemTemplate>
                                                    </asp:TemplateField>
                                                    <asp:TemplateField HeaderText="Territory"> 
                                                        <ItemTemplate> 
                                                            <asp:TextBox ID="txtTerritory" runat="server" Text='<%#Eval("AGN_TERR_AGTMGR_CD") %>'/>
                                                        </ItemTemplate>                                        
                                                    </asp:TemplateField>
                                                    <asp:TemplateField HeaderText="Market"> 
                                                        <ItemTemplate> 
                                                            <asp:TextBox ID="txtMarket" runat="server" Text='<%#Eval("EFS_Terr") %>'/>
                                                        </ItemTemplate>                                        
                                                    </asp:TemplateField>
                                                    <asp:TemplateField HeaderText="State"> 
                                                        <ItemTemplate> 
                                                            <asp:TextBox ID="txtState" runat="server" Text='<%#Eval("AGN_STATE_CD") %>'/>
                                                        </ItemTemplate>                                        
                                                    </asp:TemplateField>
                                                    <asp:TemplateField HeaderText="Attendee Name"> 
                                                        <ItemTemplate> 
                                                            <asp:TextBox ID="txtName" runat="server" Text='<%#Eval("name") %>'/>
                                                        </ItemTemplate> 
                                                         <FooterTemplate>
                                                              <asp:ImageButton ID="ImageButton1" runat="server" Height="30px" ImageUrl="~/images/excel_logo.GIF" OnClick="ImageButton1_Click" Width="28px" />
                                                         </FooterTemplate>                                       
                                                    </asp:TemplateField>
                                                    <asp:TemplateField HeaderText="NTID"> 
                                                        <ItemTemplate> 
                                                            <asp:TextBox ID="txtNTID" runat="server" Text='<%#Eval("ntid") %>'/>
                                                        </ItemTemplate>
                                                         <FooterStyle HorizontalAlign="Right" />
                                                        <FooterTemplate>
                                                            <asp:ImageButton ID="btnEmailAttendee" runat="server" ImageUrl="~/images/Email.png" Width="100px" OnClick="btnEmailAttendee_Click" />
                                                        </FooterTemplate>                                        
                                                    </asp:TemplateField>
                                                    <asp:TemplateField> 
                                                        <%--<ItemTemplate> 
                                                            <asp:TextBox ID="txtAttended" runat="server" Text='<%#Eval("attended") %>'/>
                                                        </ItemTemplate>--%>
                                                        <FooterStyle HorizontalAlign="Right" />
                                                        <FooterTemplate>
                                                            <asp:ImageButton ID="btnAdd" runat="server" Width="170px" ImageUrl="~/images/NewAttendee.png" OnClick="btnAdd_Click"/> <----- button that addeds a new row to the gridview table
                                                        </FooterTemplate>                                           
                                                    </asp:TemplateField>
                                                    <asp:TemplateField HeaderText="Attended (check=yes/ un-checked=no">                                                 
                                                      <%--  <HeaderTemplate>                
                                                            <asp:CheckBox Text="All/None" ID="chkBxHeader" onclick="javascript:HeaderClick(this);" runat="server" />          
                                                        </HeaderTemplate>  --%>
                                                        <ItemTemplate >   
                                                            <asp:CheckBox ID="chkAttended" runat="server" Checked='<%# Convert.ToBoolean(Eval("attended").ToString() == "false" ? "false":"true")  %>'/><%-- Checked='<%# Convert.ToBoolean(Eval("attended").ToString()) %>' Checked='<%# bool.Parse(Eval("attended").ToString()) %>' OnCheckedChanged=""--%>
                                                        </ItemTemplate>
                                                        <FooterTemplate>
                                                            <asp:ImageButton ID="btnUpdateRoster" runat="server" Width="100px" ImageUrl="~/images/UpdateRoster.png" OnClick="btnUpdateRoster_Click" />
                                                        </FooterTemplate>
                                                    </asp:TemplateField>
                                                </Columns>
                                                <SelectedRowStyle ForeColor="#CCFF99" Font-Bold="True" BackColor="#009999"></SelectedRowStyle>
                                        </asp:GridView>

Open in new window


C# Code: (Save button):
       protected void imgSaveBtn_Click(object sender, EventArgs e)
        {
            foreach (var r in from GridViewRow r in gvAddDeleteParticipants.Rows where r.RowType == DataControlRowType.DataRow select r)
            {
                var NTID = (TextBox)r.FindControl("txtNTID");
                //Session["txtNTID"] = NTID;
                var lblCourseID = (Label)r.FindControl("lblCourseID");
                var Territory = (TextBox)r.FindControl("txtTerritory");
                var Market = (TextBox)r.FindControl("txtMarket");
                var State = (TextBox)r.FindControl("txtState");
                var Name = (TextBox)r.FindControl("txtName");
                string now = System.DateTime.Now.ToString();
                string courseNumber = Request.QueryString["id"].ToString();
                var Attended = (TextBox)r.FindControl("lblAttendeeID");

                    StoredProcConnect sproc = new StoredProcConnect("sp_CheckDuplicateAttendant");
                    sproc.AddParameters("NTID", "COURSENUMBER");
                    sproc.AddValues(NTID.Text, lblCourseID.Text);
                    DataSet ds = sproc.Select();

                    if (ds.Tables[0].Rows.Count == 0)
                    {
                        ConnectSQL conn = new ConnectSQL();

                        conn.Insert("(name, ntid, courseNumber, dateTimeRegistered, attended, Unregister, Territory, Market, State) VALUES ('" + Name.Text + "', '" + NTID.Text + "', '" + courseNumber + "', '" + now + "', 'false', 'N','" + Territory.Text + "', '" + Market.Text + "', '" + State.Text + "')", "_registration");

                        this.lblWelcome.Visible = true;
                        this.lblWelcome.Text = "Person has been added to this course!";
                        this.lblWelcome.ForeColor = Color.Green;
                    }

Open in new window


C# Code for the stored proc --- C# Code:  sproc.AddParameters("NTID", "COURSENUMBER")
    /// <summary>
    /// for SQL 2000 Add only string and int parameters, but SQL 2005 all types work
    /// </summary>
    /// <param name="cols"></param>
    public void AddParameters(params string[] cols)
    {
        foreach (String column in cols)
        {
            cmd.Parameters.Add("@" + column, SqlDbType.Char, 0, column);
        }
    }

Open in new window

C# code for : sproc.AddValues(NTID.Text, lblCourseID.Text);
   /// <summary>
    /// add values for the parameters
    /// </summary>
    /// <param name="cols"></param>
    public void AddValues(params string[] cols)
    {
        int i = 0;
        foreach (String column in cols)
        {
            cmd.Parameters[i].Value = column;
            i++;
        }
    }

Open in new window

C # code for DataSet ds = sproc.Select(); --- Could be were the insert is happending twice
        /// <summary>
    /// Performs a Select stored procedure, MUST have AddParams()/AddValues()
    /// </summary>
    /// <returns>DataSet</returns>
    public DataSet Select()
    {
        #region Select

        conn.Open();
        cmd.CommandType = CommandType.StoredProcedure;

        DataSet ds = new DataSet();

        try
        {
            SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);

            dataAdapter.Fill(ds);
        }
        catch (Exception ex)
        {
            string errmsg = ex.Message;
        }
        finally
        {
            conn.Close();
        }

        return ds;
        #endregion
    }

Open in new window


Thank you in advance for your time and help
0
Comment
Question by:newjeep19
2 Comments
 
LVL 25

Expert Comment

by:apeter
ID: 40281387
Can you debug ? if so can you put a break point in save method and see how many times the "foreach" is executed ?
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 2000 total points
ID: 40282232
After the submit it processed the first time, use a Response.Redirect to the page to lose the fact that you are in a POST operation.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Sometimes MS breaks things just for fun... In Access 2003, only the maximum allowable SQL string length could cause problems as you built a recordset. Now, when using string data in a WHERE clause, the 'identifier' maximum is 128 characters. So, …
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question