asp.net gridview data insert two times how to avoid repeate

RAVI 1,076 Reputation points
2024-11-20T03:38:06.81+00:00

Hello

This is my gridview data on button click i have foreach insert query

User's image

most of them time it insert only one time but sometime it insert like this how to avoid duplicate insert

User's image

Developer technologies | ASP.NET | Other
{count} votes

3 answers

Sort by: Most helpful
  1. RAVI 1,076 Reputation points
    2024-11-20T07:41:54.8766667+00:00

    how to avoid duplicate insert of gridview data using asp.net c# on button click for example

    SqlConnection zcon = new SqlConnection(ConfigurationManager.ConnectionStrings["invConnectionString"].ConnectionString);
                    zcon.Open();
                    foreach (GridViewRow gvr in GridView3.Rows)
                    {
                       
                       string data1 = ((Label)gvr.FindControl("L1")).Text;
                       string data2 = ((Label)gvr.FindControl("L2")).Text;
       	           string data3 = ((Label)gvr.FindControl("L3")).Text;
    
                        SqlCommand ck = new SqlCommand("Insert into Store(Format,Name,Qty)values(@Format,@Name,@Qty)", zcon);
    
                        ck.Parameters.Add(new SqlParameter("@Format", data1));
                        ck.Parameters.Add(new SqlParameter("@Name", data2));
                        ck.Parameters.Add(new SqlParameter("@Card_Qty", data3));  
                        ck.ExecuteNonQuery();
    
                    }
    
    

    My gridview has only this data

    11111

    sometimes it goes two times to sql database table or more how to avoid such duplicates..


  2. AgaveJoe 30,491 Reputation points
    2024-11-20T10:34:47.8366667+00:00

    sometime it saving two or more times how to avoid such duplication You did not explain the source of the double entry or why a duplicate entry is a problem in your unknown design. Could it be the user double click a button? Maybe the submitted submitted fields should be unique?

    If we assume your design requires uniqueness, simply check if the record exists before adding the record. If there is a unique combination of fields in your design then add a unique constraint to the table.

    IF NOT EXISTS(SELECT (1) FROM Store WHERE Format = @Format AND Name = @Name AND Qty = @Qty)
        Insert into Store(Format,Name,Qty) values(@Format,@Name,@Qty)
    
    
    

    If you are trying to stop a user from double clicking the submit button then write a JavaScript click handler to and disable the button. We cannot see your markup so at this point it is not clear how to approach the JavaScript application. There are many online examples of disabling a button, just do a Google search.

    https://www.google.com/search?q=JAvaScript+stop+submit+button+double+click+in+web+forms

    0 comments No comments

  3. Anonymous
    2024-11-22T13:48:51.5966667+00:00

    Hi @RAVI,

    You could try this code below code this will help you insert the data in the database and on duplicate insert it will show the log in the console.

    WebForm1.aspx

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>GridView Example</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False" GridLines="Both">
                    <Columns>
                        <asp:TemplateField HeaderText="Format">
                            <ItemTemplate>
                                <asp:Label ID="L1" runat="server" Text='<%# Eval("Format") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                                <asp:Label ID="L2" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Qty">
                            <ItemTemplate>
                                <asp:Label ID="L3" runat="server" Text='<%# Eval("Qty") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
                <br />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
            </div>
        </form>
    </body>
    </html>
    

    WebForm1.aspx.cs:

    using System;
    using System.Collections.Generic;
    using System.Data.SqlClient;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Configuration;
    namespace WebApplication1
    {
        public partial class WebForm1 : System.Web.UI.Page
        {
            string connectionString = "Data Source=.;Initial Catalog=GridViewDB;Integrated Security=True";
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    LoadGridView();
                }
            }
            private void LoadGridView()
            {
                // Simulate sample data
                DataTable dt = new DataTable();
                dt.Columns.Add("Format");
                dt.Columns.Add("Name");
                dt.Columns.Add("Qty");
                dt.Rows.Add("F1", "A1", 10);
                dt.Rows.Add("F1", "B4", 20);
                dt.Rows.Add("F1", "D3", 30);
                dt.Rows.Add("F1", "KL", 40);
                GridView3.DataSource = dt;
                GridView3.DataBind();
            }
            protected void btnSubmit_Click(object sender, EventArgs e)
            {
                using (SqlConnection zcon = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
                {
                    try
                    {
                        zcon.Open();
                        foreach (GridViewRow gvr in GridView3.Rows)
                        {
                            string data1 = ((Label)gvr.FindControl("L1"))?.Text;
                            string data2 = ((Label)gvr.FindControl("L2"))?.Text;
                            string data3 = ((Label)gvr.FindControl("L3"))?.Text;
                            // Debug: Log each row data to ensure it's accessible
                            System.Diagnostics.Debug.WriteLine($"Processing Row: Format={data1}, Name={data2}, Qty={data3}");
                            SqlCommand checkCmd = new SqlCommand("SELECT COUNT(*) FROM Store WHERE Format = @Format AND Name = @Name AND Qty = @Qty", zcon);
                            checkCmd.Parameters.AddWithValue("@Format", data1);
                            checkCmd.Parameters.AddWithValue("@Name", data2);
                            checkCmd.Parameters.AddWithValue("@Qty", data3);
                            int count = (int)checkCmd.ExecuteScalar();
                            if (count == 0) // Insert only if the record doesn't exist
                            {
                                SqlCommand insertCmd = new SqlCommand("INSERT INTO Store (Format, Name, Qty) VALUES (@Format, @Name, @Qty)", zcon);
                                insertCmd.Parameters.AddWithValue("@Format", data1);
                                insertCmd.Parameters.AddWithValue("@Name", data2);
                                insertCmd.Parameters.AddWithValue("@Qty", data3);
                                insertCmd.ExecuteNonQuery();
                                // Debug: Log successful insertion
                                System.Diagnostics.Debug.WriteLine($"Inserted: Format={data1}, Name={data2}, Qty={data3}");
                            }
                            else
                            {
                                // Debug: Log duplicate row
                                System.Diagnostics.Debug.WriteLine($"Duplicate Skipped: Format={data1}, Name={data2}, Qty={data3}");
                            }
                        }
                        Response.Write("Data submitted successfully!");
                    }
                    catch (Exception ex)
                    {
                        Response.Write("Error: " + ex.Message);
                    }
                }
            }
        }
    }
    
    
    

    User's image

    Best Regards,

    Jalpa


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.