locked
gridview no duplicate value should be entered RRS feed

  • Question

  • User1126057398 posted

    Using jquery, how can one restrict duplicate value shouldn't be entered in gridview when one clicks 'Add' button. Eg. let's say one product detail ie product code,etc. is added in grid, then, same detail can't be entered again.

    Thursday, June 20, 2019 6:28 PM

Answers

  • User288213138 posted

    Hi  geetasks,

    According to your description, I made a demo for you as a reference. I used Ajax to insert data into the database.

    In my code, I define a value of a=1 and then determine if the value entered is the same as the value in the GridView. If values are same, then alert a warning, otherwise insert the database.

     The code:

    <script type="text/javascript">   
    
            $(document).ready(function () {
                $('#txtName').blur(function () {
                    var Name = $('#txtName').val();
                    var a = 1;
                    $("#<%=GridView1.ClientID%> tr td").each(function () {      
                        if (Name == $(this).text()) {
                            alert("duplicate value")
                            a = 2;
                        }
                    })
                    if (a = 1) {
                        $('#Button1').click(function () {
                            $.ajax({
                                type: 'POST',
                                contentType: "application/json; charset=utf-8",
                                url: 'WebForm99.aspx/Insert_Data',
                                data: "{'Name':'" + Name + "'}",
                                async: false,
                                success: function () {
                                    $("#GridView1 tbody").append("<tr><td>" + $('#txtName').val() + "</td></tr>")
                                    $('#txtName').val("");
                                },
                               
                            });
                        })
                    }
                });
            });
    
    </script>
    <form id="form1" runat="server">
            <div>
                <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
           
    
                <hr />
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
                    <Columns>
                        <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                    </Columns>             
                </asp:GridView>
                <input type="button" id="Button1" value="Save" />
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CaseTestConnectionString %>" SelectCommand="SELECT [Name] FROM [Test14]"></asp:SqlDataSource>
            </div>
        </form>
    
    Aspx.cs:
    [WebMethod]
            public static void Insert_Data(string Name)
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["constr527"].ConnectionString);
                conn.Open();
                SqlCommand cmd = new SqlCommand("Insert into Test14 (Name) values(@Name)", conn);
                cmd.Parameters.AddWithValue("@Name", Name);
                cmd.ExecuteNonQuery();
                conn.Close();
            }
    

    The result:

    Best regards,

    Sam

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, June 21, 2019 7:54 AM
  • User1126057398 posted

    I had checked that like below. Here 'hfActivityNameIds' contain comma separated codes anf 'hfActivityNameId.' contain what I am trying to check if exists.

    function isDataFilled() { 
    var autoCompleteBox = $find("<%= txtSearchActivity.ClientID %>");  //telerik autocomplete

    if ($("#<%=dlActivityName.ClientID %>").val() !='')
    $('#<%=hfActivityNameId.ClientID%>').val($('#<%=dlActivityName.ClientID %>').val());

    if ($("#<%=txtSearchActivity.ClientID %>").val() != '')
    $('#<%=hfActivityNameId.ClientID%>').val(autoCompleteBox.get_entries().getEntry(0).get_value().split('|')[2]);

    if ($('#<%=hfActivityNameIds.ClientID%>').val() != '') {
    // alert($('#<%=hfActivityNameIds.ClientID%>').val()); alert($('#<%=hfActivityNameId.ClientID%>').val().split('|')[0]);
    var arr = $('#<%=hfActivityNameIds.ClientID%>').val().split(',');
    var exists = arr.indexOf($('#<%=hfActivityNameId.ClientID%>').val().split('|')[0]);
    if (exists !== -1) // Original string contains value in hfActivityNameId
    {
    alert('Details corresponding to this activity already exists!!!');
    autoCompleteBox.get_entries().clear();
    return false;
    }
    //alert(exists);
    }

    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 3, 2019 7:27 AM

All replies

  • User-1038772411 posted

    Hello geetasks,

    Try with this, I hope this will help you.

    <div>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript">
            function AddRow() {
                var operator = $("[id*=txtoperator]").val();
                var value1 = $("[id*= txtvalue1]").val();
                var value2 = $("[id*= txtvalue2]").val();
                var total = $("[id*= txttotal]").val();
                if (operator != "" && value1 != "" && value2 != "" && total != "") {
                    var gridRows = $("[id *= data_gridview] tr")
                    var isExist = false;
                    gridRows.each(function () {
                        if ($("td:nth-child(1)", $(this)).html() == operator && $("td:nth-child(2)", $(this)).html() == value1 && $("td:nth-child(3)", $(this)).html() == value2 && $("td:nth-child(4)", $(this)).html() == total) {
                            isExist = true;
                        }
                    });
                    if (!isExist) {
                        row = $("[id*=data_gridview] tr:last-child").clone(true);
                        $("td:nth-child(1)", row).html(operator);
                        $("td:nth-child(2)", row).html(value1);
                        $("td:nth-child(3)", row).html(value2);
                        $("td:nth-child(4)", row).html(total)
                        $("[id*=data_gridview] tbody tr:first").after(row);
                        $("[id*=txtoperator]").val('');
                        $("[id*= txtvalue1]").val('');
                        $("[id*= txtvalue2]").val('');
                        $("[id*= txttotal]").val('');
                    } else {
                        alert("The Value already Exist ");
                    }
                }
                return false;
            };        
        </script>
        <asp:TextBox ID="txtoperator" runat="server" class="myclass" Height="16px" Width="50px"
            MaxLength="5"></asp:TextBox>
        <asp:TextBox ID="txtvalue1" runat="server" class="myclass" Height="16px" Width="50px"
            MaxLength="5"></asp:TextBox>
        <asp:TextBox ID="txtvalue2" runat="server" class="myclass" Height="16px" Width="50px"
            MaxLength="5"></asp:TextBox>
        <asp:TextBox ID="txttotal" runat="server" class="myclass" Height="16px" Width="50px"
            MaxLength="5"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="btnAddRow" Text="Add Row" runat="server" OnClientClick="return AddRow();" />
        <asp:GridView ID="data_gridview" runat="server" />
    </div>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
            {
                DataTable dt = new DataTable();
                dt.Columns.AddRange(new DataColumn[4] { new DataColumn("Opertor ",typeof(string)),
                                    new DataColumn("Value1", typeof(string)),
                                    new DataColumn("Value2", typeof(string)),
                                    new DataColumn("Result", typeof(string))});
                dt.Rows.Add("", "", "", "");
                data_gridview.DataSource = dt;
                data_gridview.DataBind();
            }
    }

    Thank you.

    Friday, June 21, 2019 5:50 AM
  • User288213138 posted

    Hi  geetasks,

    According to your description, I made a demo for you as a reference. I used Ajax to insert data into the database.

    In my code, I define a value of a=1 and then determine if the value entered is the same as the value in the GridView. If values are same, then alert a warning, otherwise insert the database.

     The code:

    <script type="text/javascript">   
    
            $(document).ready(function () {
                $('#txtName').blur(function () {
                    var Name = $('#txtName').val();
                    var a = 1;
                    $("#<%=GridView1.ClientID%> tr td").each(function () {      
                        if (Name == $(this).text()) {
                            alert("duplicate value")
                            a = 2;
                        }
                    })
                    if (a = 1) {
                        $('#Button1').click(function () {
                            $.ajax({
                                type: 'POST',
                                contentType: "application/json; charset=utf-8",
                                url: 'WebForm99.aspx/Insert_Data',
                                data: "{'Name':'" + Name + "'}",
                                async: false,
                                success: function () {
                                    $("#GridView1 tbody").append("<tr><td>" + $('#txtName').val() + "</td></tr>")
                                    $('#txtName').val("");
                                },
                               
                            });
                        })
                    }
                });
            });
    
    </script>
    <form id="form1" runat="server">
            <div>
                <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
           
    
                <hr />
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
                    <Columns>
                        <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                    </Columns>             
                </asp:GridView>
                <input type="button" id="Button1" value="Save" />
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CaseTestConnectionString %>" SelectCommand="SELECT [Name] FROM [Test14]"></asp:SqlDataSource>
            </div>
        </form>
    
    Aspx.cs:
    [WebMethod]
            public static void Insert_Data(string Name)
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["constr527"].ConnectionString);
                conn.Open();
                SqlCommand cmd = new SqlCommand("Insert into Test14 (Name) values(@Name)", conn);
                cmd.Parameters.AddWithValue("@Name", Name);
                cmd.ExecuteNonQuery();
                conn.Close();
            }
    

    The result:

    Best regards,

    Sam

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, June 21, 2019 7:54 AM
  • User1126057398 posted

    Thanks for replying. What I was trying to do is that in hidden field I am storing all codes separated by comma entered by user eg 10,20,30,etc. Now, what I am trying to do is if user enters say same product, then check if code exists in hidden field. if yes alert 'already enterd', otherwise save in datatable.

    Friday, June 21, 2019 9:14 AM
  • User288213138 posted

    Hi  geetasks,

    You can use $('#HiddenField1').val(Name) to get the value in the TextBox and then loop through the GridView to compare it with the value in the HiddenField.

    The code:

    <script type="text/javascript">   
    
            $(document).ready(function () {
                $('#txtName').blur(function () {
                    var Name = $('#txtName').val();
                    $('#HiddenField1').val(Name);          
                    var a =1;
                    $("#<%=GridView1.ClientID%> tr td").each(function () {
                        if ($('#HiddenField1').val() == $(this).text()) {
                            alert("duplicate value")
                            a = 2;
                        }
                    })
                    if (a = 1) {
                        $('#Button1').click(function () {
                            $.ajax({
                                type: 'POST',
                                contentType: "application/json; charset=utf-8",
                                url: 'WebForm99.aspx/Insert_Data',
                                data: "{'Name':'" + Name + "'}",
                                async: false,
                                success: function () {
                                    $("#GridView1 tbody").append("<tr><td>" + $('#txtName').val() + "</td></tr>")
                                    $('#txtName').val("");
                                },
                               
                            });
                        })
                    }
                });
            });
    
        </script>
    <div>
                <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                <asp:HiddenField ID="HiddenField1" runat="server"/>
                <hr />
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
                    <Columns>
                        <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                    </Columns>
                </asp:GridView>
                <input type="button" id="Button1" value="Save" />
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CaseTestConnectionString %>" SelectCommand="SELECT [Name] FROM [Test14]"></asp:SqlDataSource>
            </div>
    
    Aspx.cs:
    [WebMethod]
            public static void Insert_Data(string Name)
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["constr527"].ConnectionString);
                conn.Open();
                SqlCommand cmd = new SqlCommand("Insert into Test14 (Name) values(@Name)", conn);
                cmd.Parameters.AddWithValue("@Name", Name);
                cmd.ExecuteNonQuery();
                conn.Close();
            }
    

    The result:

    Best regards,

    Sam

    Tuesday, June 25, 2019 8:52 AM
  • User977545975 posted

    Thanks! :-)

    Monday, July 1, 2019 2:15 PM
  • User1126057398 posted

    I had checked that like below. Here 'hfActivityNameIds' contain comma separated codes anf 'hfActivityNameId.' contain what I am trying to check if exists.

    function isDataFilled() { 
    var autoCompleteBox = $find("<%= txtSearchActivity.ClientID %>");  //telerik autocomplete

    if ($("#<%=dlActivityName.ClientID %>").val() !='')
    $('#<%=hfActivityNameId.ClientID%>').val($('#<%=dlActivityName.ClientID %>').val());

    if ($("#<%=txtSearchActivity.ClientID %>").val() != '')
    $('#<%=hfActivityNameId.ClientID%>').val(autoCompleteBox.get_entries().getEntry(0).get_value().split('|')[2]);

    if ($('#<%=hfActivityNameIds.ClientID%>').val() != '') {
    // alert($('#<%=hfActivityNameIds.ClientID%>').val()); alert($('#<%=hfActivityNameId.ClientID%>').val().split('|')[0]);
    var arr = $('#<%=hfActivityNameIds.ClientID%>').val().split(',');
    var exists = arr.indexOf($('#<%=hfActivityNameId.ClientID%>').val().split('|')[0]);
    if (exists !== -1) // Original string contains value in hfActivityNameId
    {
    alert('Details corresponding to this activity already exists!!!');
    autoCompleteBox.get_entries().clear();
    return false;
    }
    //alert(exists);
    }

    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 3, 2019 7:27 AM